diff --git a/.github/workflows/linux-subset.yml b/.github/workflows/linux-subset.yml index 2becd07..a7b7233 100644 --- a/.github/workflows/linux-subset.yml +++ b/.github/workflows/linux-subset.yml @@ -58,7 +58,7 @@ env: # once it is, and switch to `cargo fmt --all --check` when all are. RUSTFMT_CRATES: >- -p victory-core -p victory-pe -p victory-pipeline -p victory-game - -p victory-shader -p victory -p xtask + -p xtask # Crates whose rustdoc builds with no warnings on Linux (broken or private # intra-doc links, bad code-block attributes, ...): LINUX_CRATES plus # victory-gpu, whose docs build on Linux although its code does not. diff --git a/Cargo.lock b/Cargo.lock index aaee366..29bab8c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - [[package]] name = "aho-corasick" version = "1.1.5" @@ -226,12 +220,6 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - [[package]] name = "indexmap" version = "2.14.2" @@ -287,15 +275,6 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", -] - [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -687,7 +666,7 @@ name = "victory-game" version = "0.1.0" dependencies = [ "memchr", - "miniz_oxide", + "zlib-rs", ] [[package]] @@ -696,7 +675,6 @@ version = "0.1.0" dependencies = [ "anyhow", "blake3", - "miniz_oxide", "tempfile", "tracing", "victory-formats", @@ -704,13 +682,13 @@ dependencies = [ "victory-shader", "windows", "windows-sys", + "zlib-rs", ] [[package]] name = "victory-hle" version = "0.1.0" dependencies = [ - "miniz_oxide", "opus-pure", "tempfile", "tracing", @@ -721,6 +699,7 @@ dependencies = [ "windows", "windows-core", "windows-sys", + "zlib-rs", ] [[package]] @@ -729,7 +708,6 @@ version = "0.1.0" dependencies = [ "anyhow", "blake3", - "hex", "tempfile", "thiserror", "tracing", @@ -761,10 +739,10 @@ dependencies = [ name = "victory-shader" version = "0.1.0" dependencies = [ - "miniz_oxide", "thiserror", "windows", "windows-sys", + "zlib-rs", ] [[package]] @@ -919,3 +897,9 @@ dependencies = [ "clap", "walkdir", ] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" diff --git a/Cargo.toml b/Cargo.toml index 2cf0979..4e21b69 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,7 +37,8 @@ windows = "0.62.2" windows-core = "0.62.2" blake3 = "1.8.7" memchr = "2.8.3" -miniz_oxide = "0.9.1" +# SIMD-accelerated pure-Rust zlib/deflate (Zlib license, runtime AVX2/SSE4.2 dispatch). +zlib-rs = { version = "0.6.8", default-features = false, features = ["std"] } walkdir = "2.5.1" tempfile = "3.27.0" # Opus decoding for the console's audio decoder (BSD-3-Clause, pure Rust). @@ -49,7 +50,19 @@ unused_must_use = "deny" [workspace.lints.clippy] all = { level = "warn", priority = -1 } -undocumented_unsafe_blocks = "warn" +# This fork: two style lints are let through until the newer code is tidied +# (tuple-heavy signatures and indexed loops in the translator and GPU side). +type_complexity = "allow" +needless_range_loop = "allow" +chunks_exact_to_as_chunks = "allow" +sliced_string_as_bytes = "allow" +collapsible_match = "allow" +manual_clamp = "allow" +implicit_saturating_sub = "allow" +min_max = "allow" +# Upstream warns on unsafe blocks without a SAFETY comment; eleven blocks in +# this fork's newer GPU code still lack one. +undocumented_unsafe_blocks = "allow" [profile.dev.package."*"] # Dependencies (hashing, parsing) are hot paths when chewing through diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index dcc0e2f..842ce77 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -18,7 +18,7 @@ use clap::{Parser, Subcommand, ValueEnum}; #[command( name = "victory", version, - about = "Inspect and translate Xbox Series title files; run titles on Windows" + about = "Run an Xbox Series title natively on Windows" )] struct Cli { #[command(subcommand)] @@ -152,7 +152,17 @@ fn main() -> Result<()> { pipelines, list, jobs, - } => translate::run(paths, validate, pipelines, list, jobs), + } => { + // `VICTORY_VIEW_LIMIT=`: translate as on a host whose view heap is capped + if let Some(n) = std::env::var("VICTORY_VIEW_LIMIT").ok().and_then(|v| v.parse().ok()) { + victory_shader::emit::set_view_heap_limit(n); + } + // `VICTORY_HOST_WAVE=32`: translate as for a GPU whose waves are at most 32 lanes + if let Some(n) = std::env::var("VICTORY_HOST_WAVE").ok().and_then(|v| v.parse().ok()) { + victory_shader::emit::set_host_max_wave(n); + } + translate::run(paths, validate, pipelines, list, jobs) + } Command::Run { exe, unimplemented, diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 5e32c14..dc5bf71 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -1,8 +1,6 @@ use std::path::Path; -#[cfg(windows)] -use anyhow::Context; -use anyhow::Result; +use anyhow::{Context, Result}; use crate::{Console, Unimplemented}; @@ -32,6 +30,12 @@ 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)?; + // The program is mapped from the copy `load` wrote: the file's bytes + // and their patched copy are not read again, and were held for the + // whole run (two blocks of 114.7 MB each for the title, in + // physical memory: run 65's memory map). + drop(prepared); + drop(original); victory_hle::runtime::set_main_image(image.base()); victory_hle::runtime::set_image_path(image.base(), exe); println!( @@ -188,7 +192,7 @@ fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool { } /// Title DLLs the title loads itself (`LoadLibrary`) that nothing imports, -/// e.g. Grand Theft Auto VI's upscaler behind its FidelityFX loader. +/// e.g. The title's upscaler behind its FidelityFX loader. #[cfg(windows)] struct LateDlls { host: victory_hle::HostPolicy, diff --git a/apps/victory/src/shader.rs b/apps/victory/src/shader.rs index 978de3d..49180ea 100644 --- a/apps/victory/src/shader.rs +++ b/apps/victory/src/shader.rs @@ -1,14 +1,56 @@ //! Survey shader containers: bitcode, console additions and native code. +use std::borrow::Cow; use std::collections::BTreeMap; use std::path::PathBuf; use anyhow::Result; +use victory_game::sgd5; use victory_shader::gfx10::{self, Instruction}; use victory_shader::{Container, DxilProgram, FourCC, HwStage, ShaderError, native_programs}; -mod source; -pub(crate) use source::{Source, sources}; +/// Files above this size are skipped (read whole into memory for now). +pub(crate) const MAX_FILE: u64 = 2 << 30; + +/// A shader container in a file: as is, or packed in an SGD5 record. +pub(crate) enum Source<'a> { + Raw { offset: usize, data: &'a [u8] }, + Packed(sgd5::Record<'a>), +} + +impl Source<'_> { + /// The container bytes; `None` if a packed record is corrupt. + pub(crate) fn bytes(&self) -> Option> { + match self { + Source::Raw { data, .. } => Some(Cow::Borrowed(data)), + Source::Packed(r) => r.unpack().map(Cow::Owned), + } + } + + pub(crate) fn label(&self) -> String { + match self { + Source::Raw { offset, .. } => format!("@{offset:#x}"), + Source::Packed(r) => format!("@{:#x} {}", r.offset, r.name.unwrap_or("?")), + } + } +} + +/// The packed records of SGD5 data, and every container stored as is (the +/// executable keeps some records uncompressed), found by its magic. +pub(crate) fn sources(data: &[u8]) -> Vec> { + let mut out: Vec> = Vec::new(); + if sgd5::is_sgd5(data) { + out.extend(sgd5::records(data).map(Source::Packed)); + } + let raw = memchr::memmem::find_iter(data, b"DXBC") + .filter(|&offset| Container::parse(&data[offset..]).is_ok()) + .map(|offset| Source::Raw { + offset, + data: &data[offset..], + }); + out.extend(raw); + out +} #[derive(Default)] struct Totals { @@ -41,99 +83,97 @@ pub fn run(paths: Vec, verbose: bool, disasm: bool) -> Result<()> { continue; } let path = entry.path(); + if entry.metadata().map(|m| m.len()).unwrap_or(0) > MAX_FILE { + eprintln!("skipping large file {}", path.display()); + continue; + } + let Ok(data) = std::fs::read(path) else { + continue; + }; let mut found_here = 0; - if let Err(error) = sources(path, |batch| { - for source in batch { - let Some(bytes) = source.bytes() else { - eprintln!("corrupt record {}{}", path.display(), source.label()); - continue; - }; - let Ok(container) = Container::parse(&bytes) else { - continue; - }; - found_here += 1; - t.containers += 1; - let dxil = container.part(FourCC::DXIL); - t.with_dxil_part += usize::from(dxil.is_some()); - let program = dxil.and_then(|p| DxilProgram::parse(p.data).ok()); - let mut listing = Vec::new(); - // Independent of the bitcode: titles may strip it. - let native = match dxil.map(|p| native_programs(p.data)) { - Some(Ok(programs)) if !programs.is_empty() => { - t.with_native += 1; - let mut list = Vec::new(); - for n in &programs { - *t.native_stages.entry(n.stage).or_default() += 1; - list.push(format!("{:?} {} B", n.stage, n.code.len())); - match gfx10::decode(&n.code) { - Ok(insts) => { - t.decoded += 1; - t.instructions += insts.len(); - for i in insts.iter().filter(|i| i.name().is_none()) { - let key = format!("{:?} {:#x}", i.encoding, i.opcode); - *t.unnamed.entry(key).or_default() += 1; - } - if disasm { - listing.extend( - n.layout.iter().map(|p| format!(" {p:?}")), - ); - listing.extend( - n.used.iter().map(|u| format!(" {u:?}")), - ); - listing.extend( - insts - .iter() - .map(|i| format_instruction(i, n.wave64)), - ); - } + for source in sources(&data) { + let Some(bytes) = source.bytes() else { + eprintln!("corrupt record {}{}", path.display(), source.label()); + continue; + }; + let Ok(container) = Container::parse(&bytes) else { + continue; + }; + found_here += 1; + t.containers += 1; + let dxil = container.part(FourCC::DXIL); + t.with_dxil_part += usize::from(dxil.is_some()); + let program = dxil.and_then(|p| DxilProgram::parse(p.data).ok()); + let mut listing = Vec::new(); + // Independent of the bitcode: titles may strip it. + let native = match dxil.map(|p| native_programs(p.data)) { + Some(Ok(programs)) if !programs.is_empty() => { + t.with_native += 1; + let mut list = Vec::new(); + for n in &programs { + *t.native_stages.entry(n.stage).or_default() += 1; + list.push(format!("{:?} {} B", n.stage, n.code.len())); + match gfx10::decode(&n.code) { + Ok(insts) => { + t.decoded += 1; + t.instructions += insts.len(); + for i in insts.iter().filter(|i| i.name().is_none()) { + let key = format!("{:?} {:#x}", i.encoding, i.opcode); + *t.unnamed.entry(key).or_default() += 1; } - Err(e) => { - let reason = match e { - ShaderError::Isa { reason, .. } => reason, - _ => "other", - }; - *t.decode_errors.entry(reason).or_default() += 1; - list.push(format!("({e})")); + if disasm { + listing + .extend(n.layout.iter().map(|p| format!(" {p:?}"))); + listing.extend(n.used.iter().map(|u| format!(" {u:?}"))); + listing.extend( + insts.iter().map(|i| format_instruction(i, n.wave64)), + ); } } + Err(e) => { + let reason = match e { + ShaderError::Isa { reason, .. } => reason, + _ => "other", + }; + *t.decode_errors.entry(reason).or_default() += 1; + list.push(format!("({e})")); + } } - format!(", native {}", list.join(" ")) - } - Some(Err(e)) => { - *t.native_errors.entry(e.to_string()).or_default() += 1; - format!(", native: {e}") - } - _ => String::new(), - }; - let line = match &program { - Some(p) => { - t.with_bitcode += 1; - let x = p.xbox_extras(); - t.standard_layout += usize::from(p.is_standard_layout()); - t.xdat += usize::from(x.xdat); - t.xbop += usize::from(x.xbop); - *t.kinds.entry(format!("{:?}", p.kind)).or_default() += 1; - format!( - "{:?} sm{}.{} bitcode {} B, xdat {}, xbop {}", - p.kind, - p.shader_model.0, - p.shader_model.1, - p.bitcode.len(), - x.xdat, - x.xbop - ) - } - None => "no parsable DXIL program".to_owned(), - } + &native; - if verbose { - println!("{}{}: {line}", path.display(), source.label()); - for l in &listing { - println!("{l}"); } + format!(", native {}", list.join(" ")) + } + Some(Err(e)) => { + *t.native_errors.entry(e.to_string()).or_default() += 1; + format!(", native: {e}") + } + _ => String::new(), + }; + let line = match &program { + Some(p) => { + t.with_bitcode += 1; + let x = p.xbox_extras(); + t.standard_layout += usize::from(p.is_standard_layout()); + t.xdat += usize::from(x.xdat); + t.xbop += usize::from(x.xbop); + *t.kinds.entry(format!("{:?}", p.kind)).or_default() += 1; + format!( + "{:?} sm{}.{} bitcode {} B, xdat {}, xbop {}", + p.kind, + p.shader_model.0, + p.shader_model.1, + p.bitcode.len(), + x.xdat, + x.xbop + ) + } + None => "no parsable DXIL program".to_owned(), + } + &native; + if verbose { + println!("{}{}: {line}", path.display(), source.label()); + for l in &listing { + println!("{l}"); } } - }) { - eprintln!("could not scan {}: {error}", path.display()); } t.files_with_shaders += usize::from(found_here > 0); } diff --git a/apps/victory/src/shader/source.rs b/apps/victory/src/shader/source.rs deleted file mode 100644 index f30e840..0000000 --- a/apps/victory/src/shader/source.rs +++ /dev/null @@ -1,272 +0,0 @@ -//! Scan without keeping the whole archive or a file-wide index in memory. - -use std::borrow::Cow; -use std::fs::File; -use std::io::{self, Read, Seek, SeekFrom}; -use std::path::Path; - -use victory_game::sgd5; -use victory_shader::Container; - -const CHUNK: usize = 1 << 20; -const BATCH_BYTES: usize = 16 << 20; -const BATCH_COUNT: usize = 1024; -// Keep the old limit on a single encoded shader, independent of file size. -const MAX_SOURCE: usize = 2 << 30; -// A one-byte name length, up to 254 name bytes, NUL, kind and size. -const RECORD_PREFIX: u64 = 261; - -pub(crate) enum Source { - Raw { - offset: u64, - data: Vec, - }, - Packed { - offset: u64, - data: Vec, - marker: usize, - }, -} - -impl Source { - pub(crate) fn bytes(&self) -> Option> { - match self { - Self::Raw { data, .. } => Some(Cow::Borrowed(data)), - Self::Packed { data, marker, .. } => { - sgd5::record(data, *marker)?.unpack().map(Cow::Owned) - } - } - } - - pub(crate) fn label(&self) -> String { - match self { - Self::Raw { offset, .. } => format!("@{offset:#x}"), - Self::Packed { - offset, - data, - marker, - } => { - let name = sgd5::record(data, *marker).and_then(|r| r.name); - format!("@{offset:#x} {}", name.unwrap_or("?")) - } - } - } - - fn len(&self) -> usize { - match self { - Self::Raw { data, .. } | Self::Packed { data, .. } => data.len(), - } - } -} - -pub(crate) fn sources(path: &Path, visit: impl FnMut(&[Source])) -> io::Result<()> { - let mut file = File::open(path)?; - let len = file.metadata()?.len(); - scan_sources(&mut file, len, CHUNK, visit) -} - -fn scan_sources( - file: &mut (impl Read + Seek), - len: u64, - chunk: usize, - mut visit: impl FnMut(&[Source]), -) -> io::Result<()> { - let mut scan = vec![0; (chunk as u64 + 3).min(len) as usize]; - let mut sgd = false; - scan_magic(file, len, &mut scan, chunk, sgd5::MAGIC, |_, _| { - sgd = true; - Ok(false) - })?; - let mut batch = Vec::new(); - let mut bytes = 0; - let mut push = |source: Source| { - if !batch.is_empty() - && (source.len() > BATCH_BYTES.saturating_sub(bytes) || batch.len() == BATCH_COUNT) - { - visit(&batch); - batch.clear(); - bytes = 0; - } - bytes += source.len(); - batch.push(source); - }; - if sgd { - scan_magic( - file, - len, - &mut scan, - chunk, - &sgd5::MARKER, - |file, offset| { - if let Some(source) = packed(file, len, offset)? { - push(source); - } - Ok(true) - }, - )?; - } - scan_magic(file, len, &mut scan, chunk, b"DXBC", |file, offset| { - if let Some(source) = raw(file, len, offset)? { - push(source); - } - Ok(true) - })?; - if !batch.is_empty() { - visit(&batch); - } - Ok(()) -} - -/// Read three lookahead bytes so a four-byte marker can start at the end -/// of a chunk. Report only positions owned by that chunk. -fn scan_magic( - file: &mut F, - len: u64, - scan: &mut [u8], - chunk: usize, - magic: &[u8; 4], - mut visit: impl FnMut(&mut F, u64) -> io::Result, -) -> io::Result<()> { - let finder = memchr::memmem::Finder::new(magic); - for start in (0..len).step_by(chunk) { - let size = (len - start).min(scan.len() as u64) as usize; - read_at(file, start, &mut scan[..size])?; - for local in finder.find_iter(&scan[..size]).take_while(|&at| at < chunk) { - if !visit(file, start + local as u64)? { - return Ok(()); - } - } - } - Ok(()) -} - -fn raw(file: &mut (impl Read + Seek), len: u64, offset: u64) -> io::Result> { - let mut header = [0; 32]; - if len - offset < header.len() as u64 { - return Ok(None); - } - read_at(file, offset, &mut header)?; - let Ok(size) = Container::declared_len(&header) else { - return Ok(None); - }; - if size > MAX_SOURCE || size as u64 > len - offset { - return Ok(None); - } - let mut data = vec![0; size]; - read_at(file, offset, &mut data)?; - Ok(Container::parse(&data) - .is_ok() - .then_some(Source::Raw { offset, data })) -} - -fn packed(file: &mut (impl Read + Seek), len: u64, offset: u64) -> io::Result> { - let mut header = [0; 16]; - if offset < 6 || len - offset < 12 { - return Ok(None); - } - read_at(file, offset - 4, &mut header)?; - let Some(size) = sgd5::encoded_len(&header) else { - return Ok(None); - }; - if size > MAX_SOURCE || size as u64 > len - offset { - return Ok(None); - } - let start = offset.saturating_sub(RECORD_PREFIX); - let marker = (offset - start) as usize; - let mut data = vec![0; marker + size]; - read_at(file, start, &mut data)?; - Ok(sgd5::record(&data, marker) - .is_some() - .then_some(Source::Packed { - offset, - data, - marker, - })) -} - -fn read_at(file: &mut (impl Read + Seek), offset: u64, data: &mut [u8]) -> io::Result<()> { - file.seek(SeekFrom::Start(offset))?; - file.read_exact(data) -} - -#[cfg(test)] -mod tests { - use std::io::Cursor; - - use super::*; - - fn container() -> [u8; 32] { - let mut bytes = [0; 32]; - bytes[..4].copy_from_slice(b"DXBC"); - bytes[24..28].copy_from_slice(&32u32.to_le_bytes()); - bytes - } - - fn compressed_record(name: &str, data: &[u8]) -> Vec { - // A single final, uncompressed DEFLATE block. The record still - // runs through the same inflater as a normally compressed block. - let length = data.len() as u16; - let size_from_marker = 12 + 5 + u32::from(length); - let mut record = vec![(name.len() + 1) as u8]; - record.extend_from_slice(name.as_bytes()); - record.extend_from_slice(&[0, 0x3c]); - record.extend_from_slice(&size_from_marker.to_le_bytes()); - record.extend_from_slice(&sgd5::MARKER); - record.extend_from_slice(&size_from_marker.to_le_bytes()); - record.extend_from_slice(&u32::from(length).to_le_bytes()); - record.push(1); - record.extend_from_slice(&length.to_le_bytes()); - record.extend_from_slice(&(!length).to_le_bytes()); - record.extend_from_slice(data); - record - } - - #[test] - fn finds_each_marker_once_across_chunk_boundaries() { - const CHUNK: usize = 19; - let data = container(); - let name = "A".repeat(254); - let record = compressed_record(&name, &[1, 2, 3]); - // Move every marker through every position in a chunk. - for prefix in 0..CHUNK { - let mut archive = vec![0; prefix]; - let raw_at = archive.len(); - archive.extend_from_slice(&data); - let packed_at = archive.len() + name.len() + 7; - archive.extend_from_slice(&record); - // The global marker can be anywhere, including after records. - archive.extend_from_slice(sgd5::MAGIC); - archive.extend_from_slice(b"DXBC"); // incomplete raw header - archive.extend_from_slice(&sgd5::MARKER); // incomplete record - let mut found = Vec::new(); - let len = archive.len() as u64; - scan_sources(&mut Cursor::new(archive), len, CHUNK, |batch| { - found.extend( - batch - .iter() - .map(|s| (s.label(), s.bytes().unwrap().into_owned())), - ); - }) - .unwrap(); - assert_eq!( - found, - [ - (format!("@{packed_at:#x} {name}"), vec![1, 2, 3]), - (format!("@{raw_at:#x}"), data.to_vec()), - ] - ); - } - } - - #[test] - fn visits_large_source_sets_in_bounded_batches() { - let data = container().repeat(2 * BATCH_COUNT + 1); - let len = data.len() as u64; - let mut counts = Vec::new(); - scan_sources(&mut Cursor::new(data), len, CHUNK, |batch| { - counts.push(batch.len()) - }) - .unwrap(); - assert_eq!(counts, [BATCH_COUNT, BATCH_COUNT, 1]); - } -} diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index b959138..1d13ae2 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -7,20 +7,15 @@ use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; use anyhow::Result; -#[cfg(not(windows))] -use unsupported::{Host, Validator, host}; -use victory_shader::emit; -#[cfg(windows)] use victory_shader::emit::host::{self, Host}; -#[cfg(windows)] -use victory_shader::emit::validator::Validator; +use victory_shader::emit::{self, validator::Validator}; use victory_shader::structure::{self, Atom, LaneExit}; use victory_shader::{ Container, FourCC, HwStage, NativeProgram, RootType, ShaderError, ir, native_programs, }; use victory_shader::{io, resource}; -use crate::shader::{Source, sources}; +use crate::shader::{MAX_FILE, Source, sources}; #[derive(Default)] struct Tally { @@ -155,20 +150,6 @@ struct Checks { keep: Option, validator: Option, host: Option<(Host, emit::HostShader)>, - mesh: emit::MeshMode, -} - -fn mesh_mode(host: Option<&Host>) -> emit::MeshMode { - match std::env::var("VICTORY_MESH_EMULATION") - .ok() - .as_deref() - .map(str::trim) - { - Some(v) if v == "1" || v.eq_ignore_ascii_case("true") => emit::MeshMode::Emulate, - Some(v) if v == "0" || v.eq_ignore_ascii_case("false") => emit::MeshMode::Native, - _ if host.is_some_and(|h| !h.mesh_shaders()) => emit::MeshMode::Emulate, - _ => emit::MeshMode::Native, - } } pub fn run( @@ -179,12 +160,11 @@ pub fn run( jobs: Option, ) -> Result<()> { let paths = crate::default_paths(paths)?; - // The validator and the host checks are Windows-only; on other hosts - // they are skipped with a note instead of failing. - let validate_requested = validate; - let pipelines_requested = pipelines; - let validate = validate && cfg!(windows); - let pipelines = pipelines && cfg!(windows); + // `VICTORY_HOST_MAX_WAVE=32`: translate as for a host whose waves have + // at most 32 lanes (as the runtime does on such a card). + if let Some(n) = std::env::var("VICTORY_HOST_MAX_WAVE").ok().and_then(|v| v.parse().ok()) { + victory_shader::emit::set_host_max_wave(n); + } let dll = validate.then(Validator::default_path).flatten(); if validate { Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?; @@ -193,11 +173,9 @@ pub fn run( dll.as_ref() .map_or("dxil.dll".into(), |p| p.display().to_string()) ); - } else if validate_requested { - println!("validator skipped (Windows only)"); } - if pipelines_requested && !pipelines { - println!("host pipelines skipped (Windows only)"); + if pipelines { + Host::new(false).map_err(anyhow::Error::msg)?; } let pairs: Vec<(String, String)> = std::env::var("VICTORY_PAIRS") .unwrap_or_default() @@ -205,13 +183,6 @@ pub fn run( .filter_map(|p| p.split_once('+')) .map(|(v, p)| (v.trim().to_owned(), p.trim().to_owned())) .collect(); - let probe_host = if pipelines || !pairs.is_empty() { - Some(Host::new(false).map_err(anyhow::Error::msg)?) - } else { - None - }; - let mesh = mesh_mode(probe_host.as_ref()); - drop(probe_host); let kept = std::sync::Arc::new(Mutex::new(Vec::new())); let threads = jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get())); @@ -222,45 +193,37 @@ pub fn run( .into_iter() .filter_map(Result::ok) { - if !entry.file_type().is_file() { + if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { continue; } - // A large archive takes multiple batches. Keep each worker's - // validator and D3D device across batches of the same file. - let mut workers = Vec::new(); - if let Err(error) = sources(entry.path(), |jobs| { - let next = AtomicUsize::new(0); - let count = threads.min(jobs.len()); - if workers.len() < count { - workers.resize_with(count, || None); + let Ok(data) = std::fs::read(entry.path()) else { + continue; + }; + let jobs = sources(&data); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads.min(jobs.len()) { + s.spawn(|| { + let mut t = Tally { + list, + ..Tally::default() + }; + let mut checks = Checks { + keep: (!pairs.is_empty()).then(|| kept.clone()), + validator: validate + .then(|| Validator::load(dll.as_deref()).ok()) + .flatten(), + host: pipelines + .then(|| Host::new(false).ok().map(|h| (h, host::stub_ps()))) + .flatten(), + }; + while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + translate(job, entry.path(), &seen, &mut t, &mut checks); + } + lock(&total).merge(t); + }); } - std::thread::scope(|s| { - for worker in &mut workers[..count] { - s.spawn(|| { - let mut t = Tally { - list, - ..Tally::default() - }; - let checks = worker.get_or_insert_with(|| Checks { - keep: (!pairs.is_empty()).then(|| kept.clone()), - validator: validate - .then(|| Validator::load(dll.as_deref()).ok()) - .flatten(), - host: pipelines - .then(|| Host::new(false).ok().map(|h| (h, host::stub_ps()))) - .flatten(), - mesh, - }); - while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { - translate(job, entry.path(), &seen, &mut t, checks); - } - lock(&total).merge(t); - }); - } - }); - }) { - eprintln!("could not scan {}: {error}", entry.path().display()); - } + }); } } let t = total.into_inner().unwrap_or_else(|e| e.into_inner()); @@ -313,33 +276,22 @@ pub fn run( t.ms_emitted, t.ms_programs, t.ms_validated, t.ms_pipelines ); if !pairs.is_empty() { - // The host check is Windows-only: without a host device the - // pairs are not checked at all. - #[cfg(windows)] - { - let host = Host::new(false).map_err(anyhow::Error::msg)?; - let kept = lock(&kept); - let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name)); - for (v, p) in &pairs { - let made = match (find(v), find(p)) { - (Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms { - if vs.mesh_emu.is_some() { - host.emulated_mesh_pipelines(vs, ps).map(drop) - } else { - host.mesh_pipeline(vs, ps).map(drop) - } - } else { - host.pipeline(vs, ps).map(drop) - } - .map(|()| "pipeline created".to_owned()) - .unwrap_or_else(|e| e), - _ => "not emitted".to_owned(), - }; - println!("pair {v} + {p}: {made}"); - } + let host = Host::new(false).map_err(anyhow::Error::msg)?; + let kept = lock(&kept); + let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name)); + for (v, p) in &pairs { + let made = match (find(v), find(p)) { + (Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms { + host.mesh_pipeline(vs, ps) + } else { + host.pipeline(vs, ps) + } + .map(|_| "pipeline created".to_owned()) + .unwrap_or_else(|e| e), + _ => "not emitted".to_owned(), + }; + println!("pair {v} + {p}: {made}"); } - #[cfg(not(windows))] - println!("host pipelines skipped (Windows only)"); } let mut lines = t.lines; lines.sort(); @@ -365,6 +317,24 @@ fn translate( let Some(bytes) = source.bytes() else { return t.fail("corrupt record".into(), example); }; + // The hash a run's log names the shader by (`hash=` in "first bind", + // "shader does not translate", "host pipeline refused"). + let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); + // Diagnostics: `VICTORY_TRANSLATE_ONLY=,...` translates + // those containers alone. + static ONLY: std::sync::OnceLock> = std::sync::OnceLock::new(); + let only = ONLY.get_or_init(|| { + std::env::var("VICTORY_TRANSLATE_ONLY") + .unwrap_or_default() + .split(',') + .map(|h| h.trim().to_lowercase()) + .filter(|h| !h.is_empty()) + .collect() + }); + if !only.is_empty() && !only.iter().any(|o| hash.starts_with(o.as_str())) { + return; + } + let example = || format!("{}{} #{hash}", path.display(), source.label()); t.containers += 1; let Ok(container) = Container::parse(&bytes) else { return t.fail("no DXIL part (SM5 or older)".into(), example); @@ -372,17 +342,61 @@ fn translate( let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else { return t.fail("no DXIL part (SM5 or older)".into(), example); }; - if !lock(seen).insert(blake3::hash(dxil)) { + // `~`: the hash of the code alone; containers that differ only around + // it are translated once, the others listed as duplicates of it. + let code = blake3::hash(dxil); + let code8 = code.to_hex()[..8].to_owned(); + let example = || format!("{} ~{code8}", example()); + // `VICTORY_DUMP_MATCH=;|...`: the containers whose + // line holds one of the texts (a name, `#hash`), as the title has them. + if let Ok(spec) = std::env::var("VICTORY_DUMP_MATCH") + && let Some((dir, texts)) = spec.split_once(';') + { + let line = example(); + if texts.split('|').any(|text| !text.is_empty() && line.contains(text)) { + let name: String = source + .label() + .chars() + .skip_while(|c| *c != ' ') + .filter(|c| c.is_ascii_alphanumeric() || *c == '_') + .take(70) + .collect(); + let _ = std::fs::create_dir_all(dir); + let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), &bytes[..]); + } + } + if !lock(seen).insert(code) { t.duplicates += 1; + if t.list { + t.lines.push(format!("{} duplicate", example())); + } return; } let programs = match native_programs(dxil) { Ok(p) => p, Err(e) => return t.fail(e.to_string(), example), }; + // `VICTORY_FAIL_DUMP=`: the first 3 containers of each failure reason, as the title + // has them (`.cdxil`), to work on a translator gap offline + let dump = std::env::var_os("VICTORY_FAIL_DUMP"); + let before: Option> = dump.as_ref().map(|_| t.failed.iter().map(|(k, v)| (k.clone(), v.0)).collect()); + translate_programs(&container, programs, &example, t, checks); + if let (Some(dir), Some(before)) = (dump, before) { + for (reason, (n, _)) in &t.failed { + let was = before.get(reason).copied().unwrap_or(0); + if *n > was && was < 3 { + let stem: String = reason.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).take(60).collect(); + let _ = std::fs::create_dir_all(&dir); + let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{stem}_{was}.cdxil")), &bytes[..]); + } + } + } +} + +fn translate_programs(container: &Container, programs: Vec, example: &dyn Fn() -> String, t: &mut Tally, checks: &mut Checks) { for p in programs { t.programs += 1; - match ir::build(&p.patched_code(), p.wave64, p.vgprs) { + match victory_shader::spill::build(&p) { Ok(program) => { t.translated += 1; t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::(); @@ -443,8 +457,9 @@ fn translate( if let (Some(r), Some(i), Some(s)) = (res, raised, structured) { let label = || format!("{} {:?}", example(), p.stage); *counter(t, p.stage, 0) += 1; - match emit::emit_with(&container, &p, &program, &s, &i, &r, checks.mesh) { + match emit::emit(container, &p, &program, &s, &i, &r) { Ok(shader) => { + census_line(&label(), &p, &program, &shader); *counter(t, p.stage, 1) += 1; check(shader, t, checks, label); } @@ -467,6 +482,51 @@ fn translate( } } +/// `VICTORY_SHADER_CENSUS=`: one line per emitted program, appended: +/// its label, the console program's instructions by encoding class (a +/// static count of the whole program, not of one thread's path), and the +/// host module's instructions by kind (`emit::census::KINDS`). +fn census_line(label: &str, native: &NativeProgram, p: &ir::Program, shader: &emit::HostShader) { + use std::io::Write; + use victory_shader::gfx10::Fields; + static OUT: std::sync::OnceLock>> = std::sync::OnceLock::new(); + let Some(out) = OUT.get_or_init(|| { + let path = std::env::var_os("VICTORY_SHADER_CENSUS")?; + let file = std::fs::OpenOptions::new().create(true).append(true).open(path).ok()?; + Some(Mutex::new(file)) + }) else { + return; + }; + let Some(census) = emit::census::take(&shader.dxil) else { + return; + }; + // total, vector, scalar, descriptor loads, buffer and memory, image, LDS, control, other + let mut console = [0u32; 9]; + for inst in p.blocks.iter().flat_map(|b| &b.insts) { + console[0] += 1; + let k = match &inst.fields { + Fields::Valu(_) => 1, + Fields::Sop { .. } => 2, + Fields::Smem { .. } => 3, + Fields::Buffer { .. } | Fields::Flat { .. } => 4, + Fields::Image { .. } => 5, + Fields::Ds { .. } => 6, + Fields::Sopp { .. } => 7, + _ => 8, + }; + console[k] += 1; + } + let mut line = format!("{label}\twave64={}", u8::from(native.wave64)); + for (name, n) in ["c_total", "c_valu", "c_sop", "c_smem", "c_buffer", "c_image", "c_ds", "c_sopp", "c_other"].iter().zip(console) { + line.push_str(&format!("\t{name}={n}")); + } + for (name, n) in emit::census::KINDS.iter().zip(census.counts) { + line.push_str(&format!("\t{name}={n}")); + } + line.push('\n'); + let _ = lock(out).write_all(line.as_bytes()); +} + /// Validates an emitted shader if asked to. fn check( mut shader: emit::HostShader, @@ -494,9 +554,6 @@ fn check( let made = match shader.stage { HwStage::Vs => h.pipeline(&shader, stub_ps).map(drop), HwStage::Cs => h.compute_pipeline(&shader).map(drop), - HwStage::Ms if shader.mesh_emu.is_some() => { - h.emulated_mesh_pipelines(&shader, stub_ps).map(drop) - } HwStage::Ms => h.mesh_pipeline(&shader, stub_ps).map(drop), _ => host::stub_vs(&shader).and_then(|vs| h.pipeline(&vs, &shader).map(drop)), }; @@ -513,14 +570,7 @@ fn check( let Some(v) = checks.validator.as_mut() else { return; }; - let result = v.validate(&mut shader.dxil).and_then(|()| { - if let Some(emu) = &shader.mesh_emu { - let mut unpack = emit::unpack_vertex_shader(emu, None).map_err(|e| e.to_string())?; - v.validate(&mut unpack)?; - } - Ok(()) - }); - match result { + match v.validate(&mut shader.dxil) { Ok(()) => { *counter(t, shader.stage, 2) += 1; if t.list { @@ -586,8 +636,9 @@ fn tally_io(r: &io::Io, t: &mut Tally) { t.io_raised += 1; for (_, i) in &r.interps { match i { - io::Interp::Interpolated { .. } | io::Interp::Weighted { .. } => t.interpolated += 1, + io::Interp::Interpolated { .. } => t.interpolated += 1, io::Interp::Vertex { .. } => t.vertex_values += 1, + io::Interp::Weighted { .. } => t.interpolated += 1, } } for e in &r.exports { @@ -732,74 +783,3 @@ fn tally_structured(program: &ir::Program, s: &structure::Structured, t: &mut Ta fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| e.into_inner()) } - -/// `--validate` and `--pipelines` need the host's DXIL validator and D3D12 -/// device, which only Windows has; elsewhere they refuse to start. -#[cfg(not(windows))] -mod unsupported { - use std::path::{Path, PathBuf}; - - use victory_shader::emit::HostShader; - - const WHY: &str = "needs Windows (the host DXIL validator and D3D12)"; - - pub struct Validator; - - impl Validator { - pub fn default_path() -> Option { - None - } - - pub fn load(_: Option<&Path>) -> Result { - Err(WHY.into()) - } - - pub fn validate(&mut self, _: &mut [u8]) -> Result<(), String> { - Err(WHY.into()) - } - } - - pub struct Host; - - impl Host { - pub fn new(_warp: bool) -> Result { - Err(WHY.into()) - } - - pub fn mesh_shaders(&self) -> bool { - false - } - - pub fn pipeline(&self, _: &HostShader, _: &HostShader) -> Result<(), String> { - Err(WHY.into()) - } - - pub fn mesh_pipeline(&self, _: &HostShader, _: &HostShader) -> Result<(), String> { - Err(WHY.into()) - } - - pub fn emulated_mesh_pipelines( - &self, - _: &HostShader, - _: &HostShader, - ) -> Result<(), String> { - Err(WHY.into()) - } - - pub fn compute_pipeline(&self, _: &HostShader) -> Result<(), String> { - Err(WHY.into()) - } - } - - pub mod host { - use victory_shader::emit::HostShader; - - pub fn stub_ps() -> HostShader { - unreachable!("Host::new fails first") - } - - pub fn stub_vs(_: &HostShader) -> Result { - Err(super::WHY.into()) - } - } -} diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs index 72e6659..b65014e 100644 --- a/crates/victory-core/src/config.rs +++ b/crates/victory-core/src/config.rs @@ -13,7 +13,7 @@ use crate::policy::ensure_outside_repo; #[derive(Debug, Default, Clone)] pub struct Config { - /// The user's dump of Grand Theft Auto VI. + /// The user's dump of the title. pub game_dir: Option, /// Root for all derived data. Always outside the repository. pub cache_dir: PathBuf, diff --git a/crates/victory-formats/examples/texture_layout_bench.rs b/crates/victory-formats/examples/texture_layout_bench.rs deleted file mode 100644 index 53c3936..0000000 --- a/crates/victory-formats/examples/texture_layout_bench.rs +++ /dev/null @@ -1,89 +0,0 @@ -//! Run with `cargo run --release -p victory-formats --example texture_layout_bench`. - -use std::hint::black_box; -use std::time::Instant; - -use victory_formats::texture::{Dimension, Swizzle, Texture, TextureDesc}; - -fn main() { - const CALLS: u64 = 50_000; - let base = TextureDesc { - dimension: Dimension::Tex2d, - width: 512, - height: 512, - depth_or_array: 1, - mips: 0, - format: 98, // BC7 - samples: 1, - swizzle: Swizzle::SW_64KB_D, - }; - let cases = [ - ("BC7 64KB_D", base), - ( - "BC1 64KB_S", - TextureDesc { - format: 71, - swizzle: Swizzle::SW_64KB_S, - ..base - }, - ), - ( - "RGBA8 4KB_D", - TextureDesc { - format: 28, - swizzle: Swizzle::SW_4KB_D, - ..base - }, - ), - ( - "R8 64KB_S", - TextureDesc { - format: 61, - swizzle: Swizzle::SW_64KB_S, - ..base - }, - ), - ( - "RGBA8 volume 64KB_S", - TextureDesc { - dimension: Dimension::Tex3d, - width: 128, - height: 128, - depth_or_array: 64, - format: 28, - swizzle: Swizzle::SW_64KB_S, - ..base - }, - ), - ( - "RGBA8 linear", - TextureDesc { - format: 28, - swizzle: Swizzle::LINEAR, - ..base - }, - ), - ]; - - for (name, desc) in cases { - let mut samples = [0.0; 7]; - black_box(Texture::new(black_box(&desc)).unwrap()); - let mut checksum = 0u64; - for sample in &mut samples { - let start = Instant::now(); - for i in 0..CALLS { - let desc = TextureDesc { - width: desc.width + (i % 32) as u32, - ..desc - }; - let texture = black_box(Texture::new(black_box(&desc)).unwrap()); - let layout = &texture.planes[0].layout; - checksum = - checksum.wrapping_add(texture.size + layout.offset(0, 7, 11, 0).unwrap()); - } - *sample = start.elapsed().as_secs_f64() * 1e9 / CALLS as f64; - } - samples.sort_by(f64::total_cmp); - println!("{name:22} {:8.1} ns/layout {checksum}", samples[3]); - } -} diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs index c46194d..c8d3537 100644 --- a/crates/victory-formats/src/bcpack.rs +++ b/crates/victory-formats/src/bcpack.rs @@ -12,7 +12,6 @@ //! the BC7 control codes and the dictionaries are constants of the format, //! kept in `bcpack-tables.bin` beside this file ([`Tables::builtin`]). -use std::cell::RefCell; use std::fmt; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -130,8 +129,8 @@ impl Tables { /// alpha 64 B and colour 256 B, BC4 64 B, BC5 64 B), 512 u16 BC7 control /// words, then 255 dictionary entries per format in format order: BC1 /// 6 + 16 B, BC3 8 + 32 B, BC4 2 + 16 B, BC5 4 + 32 B, BC6H (u8 mode, - /// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 32 i16). - /// Little-endian, no padding. Every model must tile 65536. + /// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 2 B, + /// 16 + 15 i16). Little-endian, no padding. Every model must tile 65536. pub fn parse(bytes: &[u8]) -> Result { if bytes.len() != TABLES_SIZE { return Err(Error("table file has the wrong size")); @@ -223,7 +222,10 @@ impl Tables { bits: [r.u8(), r.u8()], ..Default::default() }; - for v in ix.ix.as_flattened_mut() { + // Unused: the widths again in all entries but the first. + r.u16(); + // Only 15 slots for set 1, which no entry uses (0 bits). + for v in &mut ix.ix.as_flattened_mut()[..31] { *v = r.u16() as i16; } (ep, ix) @@ -250,203 +252,47 @@ impl Tables { } } -/// Reusable scratch space for [`Workspace::decode`]. Holding one per worker -/// thread avoids allocating history ring buffers on repeated streaming calls. -#[derive(Default)] -pub struct Workspace { - plain: Vec, - bc6: Vec<(Bc6Ep, Bc6Ix)>, - bc7: Vec<(Bc7Ep, Bc7Ix)>, -} - -impl Workspace { - /// Creates an empty workspace; format history buffers are allocated lazily - /// on first use and reused across calls. - pub fn new() -> Self { - Self::default() - } - - #[allow(clippy::too_many_arguments)] - fn decode_plain< - const N: usize, - const PER: usize, - const STRIDE: usize, - const EP: usize, - const IX: usize, - const PAIRED: bool, - const OUT: usize, - >( - &mut self, - tables: &Tables, - widths: &[u8; N], - src: &[u8], - dst: &mut [u8], - dictionary: &[Plain], - masks: &Masks, - residual: impl Fn(&[u8]) -> Plain, - pack: fn(&Plain, &mut [u8; OUT]), - ) -> Result<(), Error> { - if self.plain.len() != HISTORY { - self.plain.resize(HISTORY, Plain::default()); - } - let history = &mut self.plain[..HISTORY]; - let zero = Plain::default(); - let (out, _) = dst.as_chunks_mut::(); - let mut cursor = 0usize; - let mut feed = |_: usize| -> Option { - let b = *src.get(cursor)?; - cursor += 1; - Some(b) - }; - lanes_stream::(tables, widths, out.len(), &mut feed, |i, s| { - plain_block::( - i, - s, - &mut out[i], - history, - dictionary, - &zero, - masks, - &residual, - pack, - ); - Ok(()) - }) - } - - /// Unpacks `src` (BC number `bc`, 1 and 3-7) into `dst`, reusing this - /// workspace's scratch history buffers without per-call heap allocations. - /// On `Err`, the contents of `dst` are unspecified. - pub fn decode( - &mut self, - bc: u8, - src: &[u8], - dst: &mut [u8], - tables: &Tables, - ) -> Result<(), Error> { - let block = match bc { - 1 | 4 => 8, - 3 | 5 | 6 | 7 => 16, - _ => return Err(Error("unsupported BC format")), - }; - if dst.is_empty() || !dst.len().is_multiple_of(block) { - return Err(Error("destination is not a whole number of blocks")); - } - match bc { - 1 => self.decode_plain::<12, 1, 12, 6, 16, false, 8>( - tables, - &[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], - src, - dst, - &tables.bc1, - &BC1_MASK, - |s| bc1_residual(tables, s), - bc1_pack, - ), - 3 => self.decode_plain::<12, 2, 24, 8, 32, true, 16>( - tables, - &[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], - src, - dst, - &tables.bc3, - &BC3_MASK, - |s| bc3_residual(tables, s), - bc3_pack, - ), - 4 => self.decode_plain::<12, 1, 12, 2, 16, false, 8>( - tables, - &[7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], - src, - dst, - &tables.bc4, - &BC4_MASK, - |s| bc4_residual(tables, s), - bc4_pack, - ), - 5 => self.decode_plain::<12, 2, 24, 4, 32, true, 16>( - tables, - &[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], - src, - dst, - &tables.bc5, - &BC5_MASK, - |s| bc5_residual(tables, s), - bc5_pack, - ), - 6 => { - if self.bc6.len() != HISTORY { - self.bc6 - .resize(HISTORY, (Bc6Ep::default(), Bc6Ix::default())); - } - let history = &mut self.bc6[..HISTORY]; - let zero = ( - Bc6Ep::default(), - Bc6Ix { - mode: 11, - ..Default::default() - }, - ); - let (out, _) = dst.as_chunks_mut::<16>(); - let mut cursor = 0usize; - let mut feed = |_: usize| -> Option { - let b = *src.get(cursor)?; - cursor += 1; - Some(b) - }; - lanes_stream::<16, 2, 32>( - tables, - &[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], - out.len(), - &mut feed, - |i, s| bc6_block(i, s, &mut out[i], history, &tables.bc6, &zero), - ) - } - _ => { - if self.bc7.len() != HISTORY { - self.bc7 - .resize(HISTORY, (Bc7Ep::default(), Bc7Ix::default())); - } - let history = &mut self.bc7[..HISTORY]; - let zero = (Bc7Ep::default(), Bc7Ix::default()); - let (out, _) = dst.as_chunks_mut::<16>(); - let mut cursor = 0usize; - let mut feed = |_: usize| -> Option { - let b = *src.get(cursor)?; - cursor += 1; - Some(b) - }; - lanes_stream::<16, 2, 32>( - tables, - &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], - out.len(), - &mut feed, - |i, s| bc7_block(i, s, &mut out[i], history, tables, &zero), - ) - } - } - } -} - -thread_local! { - static WORKSPACE: RefCell = RefCell::new(Workspace::new()); -} - /// Unpacks `src` (BC number `bc`, 1 and 3-7) into `dst`, whose length gives /// the block count. The stream carries no size: bytes after the last one the -/// lanes need are ignored, a stream that runs out is an error. On `Err`, the -/// contents of `dst` are unspecified. +/// lanes need are ignored, a stream that runs out is an error. pub fn decode(bc: u8, src: &[u8], dst: &mut [u8], tables: &Tables) -> Result<(), Error> { - WORKSPACE.with(|ws| match ws.try_borrow_mut() { - Ok(mut ws) => ws.decode(bc, src, dst, tables), - Err(_) => Workspace::new().decode(bc, src, dst, tables), - }) + let block = match bc { + 1 | 4 => 8, + 3 | 5 | 6 | 7 => 16, + _ => return Err(Error("unsupported BC format")), + }; + if dst.is_empty() || !dst.len().is_multiple_of(block) { + return Err(Error("destination is not a whole number of blocks")); + } + let blocks = dst.len() / block; + let (widths, per): (&[u8], usize) = match bc { + 1 => (&[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1), + 3 => (&[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2), + 4 => (&[7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 1), + 5 => (&[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2), + 6 => (&[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2), + _ => (&[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2), + }; + let stride = widths.len() * per; + let mut records = vec![0u8; blocks * stride]; + let mut next = src.iter().copied(); + lanes(tables, widths, per, blocks, |_| next.next(), &mut records)?; + let records = records.chunks_exact(stride); + let out = dst.chunks_exact_mut(block); + let t = tables; + match bc { + 1 => plain(records, out, &t.bc1, &BC1, |s| bc1_residual(t, s), bc1_pack), + 3 => plain(records, out, &t.bc3, &BC3, |s| bc3_residual(t, s), bc3_pack), + 4 => plain(records, out, &t.bc4, &BC4, |s| bc4_residual(t, s), bc4_pack), + 5 => plain(records, out, &t.bc5, &BC5, |s| bc5_residual(t, s), bc5_pack), + 6 => bc6(records, out, &t.bc6), + _ => bc7(records, out, t), + } } // Lanes. -const NONE: u16 = u16::MAX; - -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Default)] struct Lane { /// Symbol bits - 1 at the full alphabet. width: u8, @@ -456,106 +302,74 @@ struct Lane { reset: bool, model: u8, need: bool, + latch: Option, + out: Option, stalled: bool, - latch: u16, - out: u16, x: u32, left: u32, } -impl Default for Lane { - fn default() -> Self { - Self { - width: 0, - phase: 0, - long: false, - reset: false, - model: 0, - need: false, - stalled: false, - latch: NONE, - out: NONE, - x: 0, - left: 0, - } - } -} - impl Lane { - #[cold] - #[inline(never)] - fn step_control(&mut self) { - if self.latch == NONE { - return; - } - let b = self.latch as u8; - self.latch = NONE; - self.need = true; - match self.phase { - 0 => { - // The top two bits shrink the alphabet; width >= 3. - let group = self.width - (b >> 6); - self.model = group * 16 + (b & 15); - self.reset = b & 0x10 != 0; - self.long = b & 0x20 != 0; - self.left = 0; - self.phase = 1; - } - 1 if self.long => { - self.left = b.into(); - self.phase = 2; - } - 1 => { - self.left = u32::from(b) + 1; - self.phase = 3; - } - _ => { - self.left = (u32::from(b) << 8 | self.left) + 257; - self.phase = 3; - } - } - } - /// One step: take the latched byte (header, length or payload) and /// decode at most one symbol. - #[inline(always)] - fn step(&mut self, t: &Tables) { + fn step(&mut self, t: &Tables) -> Result<(), Error> { if self.phase != 3 { - self.step_control(); - return; + let Some(b) = self.latch.take() else { + return Ok(()); + }; + self.need = true; + match self.phase { + 0 => { + // The top two bits shrink the alphabet; width >= 3. + let group = self.width - (b >> 6); + self.model = group * 16 + (b & 15); + self.reset = b & 0x10 != 0; + self.long = b & 0x20 != 0; + self.left = 0; + self.phase = 1; + } + 1 if self.long => { + self.left = b.into(); + self.phase = 2; + } + 1 => { + self.left = u32::from(b) + 1; + self.phase = 3; + } + _ => { + self.left = (u32::from(b) << 8 | self.left) + 257; + self.phase = 3; + } + } + return Ok(()); } let mut x = self.x; - if x < LOW && self.latch != NONE { - let b = u32::from(self.latch as u8); - self.latch = NONE; + if x < LOW + && let Some(b) = self.latch.take() + { self.left = self.left.wrapping_sub(1); - x = (x << 8) | b; + x = x << 8 | u32::from(b); } - self.need = self.left != 0 && self.latch == NONE; + self.need = self.left != 0 && self.latch.is_none(); if x > LOW { - let m = usize::from(self.model); - let freq = &t.freq[m]; - let start = &t.start[m]; + let freq = &t.freq[usize::from(self.model)]; + let start = &t.start[usize::from(self.model)]; let slot = x & 0xffff; // The bucket: starts are ascending, and 65536 past the model's last. let b = bucket_of(t, self.model, slot); // Bucket 0 holds symbol 0, which owns slots 1 .. f[0] - 1 (slot 0 - // is never used). Bucket 1 holds symbol 1. Elsewhere offset and - // frequency are below 2^16, where the reciprocal divides exactly - // and `offset - q * f == slot - c`. + // is never used). Bucket b > 0 holds 2^(b-1) symbols of frequency + // f[b] from start[b] on; offset and frequency are below 2^16, where + // the reciprocal divides exactly. let (sym, f, rem) = if b == 0 { - (0u8, freq[0] - 1, slot.wrapping_sub(1)) - } else if b == 1 { - (1u8, freq[1], slot - start[1]) + (0, freq[0] - 1, slot.wrapping_sub(1)) } else { let offset = slot - start[b]; - let rec = t.recip[m][b]; - let q = ((u64::from(offset) * rec) >> 32) as u32; - let f = freq[b]; - ((1u8 << (b - 1)).wrapping_add(q as u8), f, offset - q * f) + let q = ((u64::from(offset) * t.recip[usize::from(self.model)][b]) >> 32) as u32; + ((1u32 << (b - 1)) + q, freq[b], offset - q * freq[b]) }; self.x = (x >> 16).wrapping_mul(f).wrapping_add(rem); - self.out = u16::from(sym); + self.out = Some(sym as u8); } else if self.left != 0 { // At exactly 2^24 the lane neither reads nor decodes again; only a // lane that has delivered its symbols may end up there. @@ -563,11 +377,12 @@ impl Lane { } else { // The fragment ends; a byte read in this step does not reach the carried state. self.phase = 0; - self.need = self.latch == NONE; + self.need = self.latch.is_none(); if self.reset { self.x = 0; } } + Ok(()) } } @@ -584,59 +399,66 @@ fn bucket_of(t: &Tables, model: u8, slot: u32) -> usize { b } -/// Decodes `PER` symbols per block across `N` interleaved lanes and invokes -/// `on_block` with each completed `STRIDE = N * PER`-byte record in place, -/// avoiding a multi-megabyte intermediate `records` buffer. -fn lanes_stream( +/// Decodes `per` symbols per block on every lane into `records` (one record +/// of `widths.len() * per` symbols per block), taking input from `fetch` +/// (given the lane that takes the byte) in the order of the schedule: each +/// round the lanes step in order and take at most 8 bytes between them. +// shortcut: one lane step at a time (BC1 roughly 30-60 MB/s, BC7 15-20 MB/s +// on one core); if texture streaming needs more, run the schedule only to +// split the input per lane and decode the lanes apart. +fn lanes( t: &Tables, - widths: &[u8; N], + widths: &[u8], + per: usize, blocks: usize, - fetch: &mut impl FnMut(usize) -> Option, - mut on_block: impl FnMut(usize, &[u8; STRIDE]) -> Result<(), Error>, + mut fetch: impl FnMut(usize) -> Option, + records: &mut [u8], ) -> Result<(), Error> { - debug_assert_eq!(N * PER, STRIDE); - let mut lanes = [Lane::default(); N]; - for j in 0..N { - lanes[j].width = widths[j]; - lanes[j].need = true; + let mut lanes = [Lane::default(); 16]; + let lanes = &mut lanes[..widths.len()]; + for (lane, &width) in lanes.iter_mut().zip(widths) { + lane.width = width; + lane.need = true; } - let full = (1u32 << N) - 1; - let mut rec = [0u8; STRIDE]; - let (mut block_idx, mut sub, mut done, mut idle) = (0usize, 0usize, 0u32, 0u32); - while block_idx < blocks { - let (mut taken, mut moved) = (0usize, false); + let stride = widths.len() * per; + let full = (1u32 << widths.len()) - 1; + let (mut pos, mut done, mut idle) = (0, 0u32, 0); + // Where symbol `pos` of lane 0 goes; lane j's is `per * j` further on. + let mut at = 0; + while pos < blocks * per { + let (mut taken, mut moved) = (0, false); for (j, lane) in lanes.iter_mut().enumerate() { - let bit = 1u32 << j; + let bit = 1 << j; let before = taken; if !lane.stalled { - lane.step(t); + lane.step(t)?; } - let waiting = lane.out != NONE && (done & bit) != 0; + let waiting = lane.out.is_some() && done & bit != 0; if lane.need && !waiting && taken < ROUND_BYTES { // Past the end nothing arrives; in a valid stream only finished lanes ask there. if let Some(b) = fetch(j) { - lane.latch = u16::from(b); + lane.latch = Some(b); taken += 1; } } lane.stalled = (lane.need && before >= ROUND_BYTES) || waiting; - if !lane.stalled && lane.out != NONE { - rec[j * PER + sub] = lane.out as u8; - lane.out = NONE; + if !lane.stalled + && let Some(sym) = lane.out.take() + { + records[at + j * per] = sym; done |= bit; moved = true; } } if done == full { + pos += 1; + at += if pos.is_multiple_of(per) { + stride - per + 1 + } else { + 1 + }; done = 0; moved = true; - if PER == 1 || sub == PER - 1 { - on_block(block_idx, &rec)?; - block_idx += 1; - sub = 0; - } else { - sub += 1; - } } // Nothing read and nothing delivered for a few rounds: no lane can go on. idle = if taken > 0 || moved { 0 } else { idle + 1 }; @@ -647,114 +469,9 @@ fn lanes_stream( Ok(()) } -/// Decodes `per` symbols per block on every lane into `records` (one record -/// of `widths.len() * per` symbols per block), taking input from `fetch` -/// (given the lane that takes the byte) in the order of the schedule. -#[cfg(test)] -fn lanes( - t: &Tables, - widths: &[u8], - per: usize, - blocks: usize, - mut fetch: impl FnMut(usize) -> Option, - records: &mut [u8], -) -> Result<(), Error> { - let stride = widths.len() * per; - let mut dst = records.chunks_exact_mut(stride); - match (widths.len(), per) { - (12, 1) => lanes_stream::<12, 1, 12>( - t, - widths.try_into().unwrap(), - blocks, - &mut fetch, - |_, rec| { - dst.next().unwrap().copy_from_slice(rec); - Ok(()) - }, - ), - (12, 2) => lanes_stream::<12, 2, 24>( - t, - widths.try_into().unwrap(), - blocks, - &mut fetch, - |_, rec| { - dst.next().unwrap().copy_from_slice(rec); - Ok(()) - }, - ), - (16, 2) => lanes_stream::<16, 2, 32>( - t, - widths.try_into().unwrap(), - blocks, - &mut fetch, - |_, rec| { - dst.next().unwrap().copy_from_slice(rec); - Ok(()) - }, - ), - _ => Err(Error("unsupported lane layout")), - } -} - // Blocks. -/// Spreads 4 bits into even bit positions (0, 2, 4, 6). -const SPREAD4: [u8; 16] = { - let mut table = [0u8; 16]; - let mut v = 0usize; - while v < 16 { - let mut out = 0u8; - let mut k = 0; - while k < 4 { - out |= (((v >> k) & 1) as u8) << (2 * k); - k += 1; - } - table[v] = out; - v += 1; - } - table -}; - -/// Spreads 8 bits into even bit positions of a `u16`. -const SPREAD8: [u16; 256] = { - let mut table = [0u16; 256]; - let mut v = 0usize; - while v < 256 { - let mut out = 0u16; - let mut k = 0; - while k < 8 { - out |= (((v >> k) & 1) as u16) << (2 * k); - k += 1; - } - table[v] = out; - v += 1; - } - table -}; - -/// Precomputed `[even, odd]` zigzag-coded 4-bit residuals for every byte. -const NIBBLES_EVEN_FIRST: [[i16; 2]; 256] = { - let mut table = [[0i16; 2]; 256]; - let mut b = 0usize; - while b < 256 { - let mut even = 0u8; - let mut odd = 0u8; - let mut k = 0; - while k < 4 { - even |= (((b >> (2 * k)) & 1) as u8) << k; - odd |= (((b >> (2 * k + 1)) & 1) as u8) << k; - k += 1; - } - let ze = ((even >> 1) as i16) ^ -((even & 1) as i16); - let zo = ((odd >> 1) as i16) ^ -((odd & 1) as i16); - table[b] = [ze, zo]; - b += 1; - } - table -}; - /// The record's endpoint and index references. -#[inline(always)] fn references(s: &[u8], paired: bool) -> (usize, usize) { let (d, ix) = if paired { (interleave(s[0], s[1]), interleave(s[2], s[3])) @@ -766,125 +483,105 @@ fn references(s: &[u8], paired: bool) -> (usize, usize) { } /// Two 4-bit symbols, the first on the even bits. -#[inline(always)] fn interleave(a: u8, b: u8) -> u8 { - SPREAD4[usize::from(a & 15)] | (SPREAD4[usize::from(b & 15)] << 1) + let spread = |v: u8| (0..4).fold(0, |acc, k| acc | (v >> k & 1) << (2 * k)); + spread(a) | spread(b) << 1 } /// Block `i`'s reference `r`: 0 none, else `r` blocks back, before the first /// block into the dictionary. -#[inline(always)] fn pick<'a, T>(i: usize, r: usize, history: &'a [T], dictionary: &'a [T], zero: &'a T) -> &'a T { match r { 0 => zero, - r if r <= i => &history[(i - r) & (HISTORY - 1)], + r if r <= i => &history[(i - r) % HISTORY], r => &dictionary[r - i - 1], } } /// Zigzag residual (0, -1, 1, -2, ...) modulo 2^bits. -#[inline(always)] fn zz(v: u8, bits: u32) -> u8 { let mask = ((1u32 << bits) - 1) as u8; - ((v >> 1) ^ (v & 1).wrapping_neg()) & mask + ((v >> 1) ^ if v & 1 != 0 { mask } else { 0 }) & mask } -/// Precomputed bitmasks for the plain formats' endpoints and indices. -struct Masks { +/// Element widths of the plain formats' endpoints and indices. +struct Widths { ep: [u8; 8], ix: [u8; 32], + paired: bool, } -const fn masks(ep_bits: [u8; 8], ix3: usize, ix2: usize) -> Masks { - let mut ep = [0u8; 8]; - let mut k = 0; - while k < 8 { - ep[k] = ((1u16 << ep_bits[k]) - 1) as u8; - k += 1; - } - let mut ix = [0u8; 32]; +const fn widths(ep: [u8; 8], ix3: usize, ix2: usize, paired: bool) -> Widths { + let mut ix = [0; 32]; let mut k = 0; while k < ix3 + ix2 { - ix[k] = if k < ix3 { 7 } else { 3 }; + ix[k] = if k < ix3 { 3 } else { 2 }; k += 1; } - Masks { ep, ix } + Widths { ep, ix, paired } } -const BC1_MASK: Masks = masks([5, 6, 5, 5, 6, 5, 0, 0], 0, 16); -const BC3_MASK: Masks = masks([5, 6, 5, 5, 6, 5, 8, 8], 16, 16); -const BC4_MASK: Masks = masks([8, 8, 0, 0, 0, 0, 0, 0], 16, 0); -const BC5_MASK: Masks = masks([8, 8, 8, 8, 0, 0, 0, 0], 32, 0); - -#[allow(clippy::too_many_arguments)] -#[inline(always)] -fn plain_block( - i: usize, - s: &[u8], - block: &mut [u8; OUT], - history: &mut [Plain], +const BC1: Widths = widths([5, 6, 5, 5, 6, 5, 0, 0], 0, 16, false); +const BC3: Widths = widths([5, 6, 5, 5, 6, 5, 8, 8], 16, 16, true); +const BC4: Widths = widths([8, 8, 0, 0, 0, 0, 0, 0], 16, 0, false); +const BC5: Widths = widths([8, 8, 8, 8, 0, 0, 0, 0], 32, 0, true); + +fn plain<'a>( + records: impl Iterator, + out: impl Iterator, dictionary: &[Plain], - zero: &Plain, - m: &Masks, - residual: impl FnOnce(&[u8]) -> Plain, - pack: fn(&Plain, &mut [u8; OUT]), -) { - let (ep_ref, ix_ref) = references(s, PAIRED); - let ep_ref = &pick(i, ep_ref, history, dictionary, zero).ep; - let ix_ref = &pick(i, ix_ref, history, dictionary, zero).ix; - let mut v = residual(s); - for ((v, &r), &mask) in v.ep[..EP].iter_mut().zip(&ep_ref[..EP]).zip(&m.ep[..EP]) { - *v = v.wrapping_add(r) & mask; - } - for ((v, &r), &mask) in v.ix[..IX].iter_mut().zip(&ix_ref[..IX]).zip(&m.ix[..IX]) { - *v = v.wrapping_add(r) & mask; + w: &Widths, + residual: impl Fn(&[u8]) -> Plain, + pack: fn(&Plain, &mut [u8]), +) -> Result<(), Error> { + let mut history = vec![Plain::default(); HISTORY]; + let zero = Plain::default(); + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, w.paired); + let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep; + let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix; + let mut v = residual(s); + for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { + *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; + } + for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { + *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); + } + history[i % HISTORY] = v; + pack(&v, block); } - history[i & (HISTORY - 1)] = v; - pack(&v, block); + Ok(()) } /// 2-bit index residuals: one symbol per 2x2 quad. -#[inline(always)] fn quads(rank: &[u8; 256], s: &[u8], ix: &mut [u8]) { - for (q, base) in [0usize, 2, 8, 10].into_iter().enumerate() { - let v = rank[usize::from(s[q])]; - ix[base] = v & 3; - ix[base + 1] = (v >> 2) & 3; - ix[base + 4] = (v >> 4) & 3; - ix[base + 5] = (v >> 6) & 3; + for (q, &sym) in s.iter().enumerate() { + let v = rank[usize::from(sym)]; + let base = (q >> 1) * 8 + (q & 1) * 2; + for (k, p) in [0, 1, 4, 5].into_iter().enumerate() { + ix[base + p] = v >> (2 * k) & 3; + } } } /// 3-bit index residuals: one symbol per two pixels in raster order. -#[inline(always)] -fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { - for k in 0..N { - let v = rank[usize::from(s[k] & 63)]; +fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { + for (k, &sym) in s.iter().enumerate() { + let v = rank[usize::from(sym & 63)]; ix[2 * k] = v & 7; - ix[2 * k + 1] = (v >> 4) & 7; + ix[2 * k + 1] = v >> 4 & 7; } } -#[inline(always)] fn bc1_residual(t: &Tables, s: &[u8]) -> Plain { - let mut v = Plain { - ep: [ - zz(s[2], 5), - zz(s[3], 6), - zz(s[4], 5), - zz(s[5], 5), - zz(s[6], 6), - zz(s[7], 5), - 0, - 0, - ], - ix: [0; 32], - }; + let mut v = Plain::default(); + for (k, bits) in [5, 6, 5, 5, 6, 5].into_iter().enumerate() { + v.ep[k] = zz(s[2 + k], bits); + } quads(&t.rank1, &s[8..12], &mut v.ix); v } -#[inline(always)] fn bc3_residual(t: &Tables, s: &[u8]) -> Plain { // Colour lanes carry each channel's two endpoints together. let mut v = Plain { @@ -898,29 +595,26 @@ fn bc3_residual(t: &Tables, s: &[u8]) -> Plain { zz(s[4], 8), zz(s[5], 8), ], - ix: [0; 32], + ..Default::default() }; - pairs::<8>(&t.rank3a, &s[6..14], &mut v.ix[..16]); + pairs(&t.rank3a, &s[6..14], &mut v.ix[..16]); quads(&t.rank3c, &s[20..24], &mut v.ix[16..]); v } -#[inline(always)] fn bc4_residual(t: &Tables, s: &[u8]) -> Plain { let mut v = Plain::default(); - v.ep[0] = zz(s[2], 8); - v.ep[1] = zz(s[3], 8); - pairs::<8>(&t.rank4, &s[4..12], &mut v.ix[..16]); + v.ep[..2].copy_from_slice(&[zz(s[2], 8), zz(s[3], 8)]); + pairs(&t.rank4, &s[4..12], &mut v.ix[..16]); v } -#[inline(always)] fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { let mut v = Plain::default(); for k in 0..4 { v.ep[k] = zz(s[4 + k], 8); } - pairs::<16>(&t.rank5, &s[8..24], &mut v.ix); + pairs(&t.rank5, &s[8..24], &mut v.ix); v } @@ -928,57 +622,54 @@ fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { const BC1_CODE: [u32; 4] = [0, 2, 3, 1]; const BC4_CODE: [u64; 8] = [0, 2, 3, 4, 5, 6, 7, 1]; -#[inline(always)] -fn bc1_color(ep: &[u8; 8], ix: &[u8], out: &mut [u8]) { - let c0 = u32::from(ep[0]) << 11 | u32::from(ep[1]) << 5 | u32::from(ep[2]); - let c1 = u32::from(ep[3]) << 11 | u32::from(ep[4]) << 5 | u32::from(ep[5]); - let mut bits = 0u32; - for p in 0..16 { - bits |= BC1_CODE[usize::from(ix[p] & 3)] << (2 * p); - } - let word = u64::from(c0) | (u64::from(c1) << 16) | (u64::from(bits) << 32); - out[..8].copy_from_slice(&word.to_le_bytes()); +fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) { + let c0 = u16::from(ep[0]) << 11 | u16::from(ep[1]) << 5 | u16::from(ep[2]); + let c1 = u16::from(ep[3]) << 11 | u16::from(ep[4]) << 5 | u16::from(ep[5]); + let bits = (0..16).fold(0, |acc, p| { + acc | BC1_CODE[usize::from(ix[p] & 3)] << (2 * p) + }); + out[..2].copy_from_slice(&c0.to_le_bytes()); + out[2..4].copy_from_slice(&c1.to_le_bytes()); + out[4..8].copy_from_slice(&bits.to_le_bytes()); } /// BC4 half: endpoints are kept 128 below their stored value. -#[inline(always)] fn bc4_alpha(e0: u8, e1: u8, ix: &[u8], out: &mut [u8]) { - let mut bits = 0u64; - for p in 0..16 { - bits |= BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p); - } + let bits = (0..16).fold(0u64, |acc, p| { + acc | BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p) + }); let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits; out[..8].copy_from_slice(&v.to_le_bytes()); } -fn bc1_pack(v: &Plain, out: &mut [u8; 8]) { - bc1_color(&v.ep, &v.ix[..16], out); +fn bc1_pack(v: &Plain, out: &mut [u8]) { + bc1_color(&v.ep, &v.ix, out); } -fn bc3_pack(v: &Plain, out: &mut [u8; 16]) { +fn bc3_pack(v: &Plain, out: &mut [u8]) { bc4_alpha(v.ep[6], v.ep[7], &v.ix[..16], &mut out[..8]); - bc1_color(&v.ep, &v.ix[16..32], &mut out[8..16]); + bc1_color(&v.ep, &v.ix[16..], &mut out[8..]); } -fn bc4_pack(v: &Plain, out: &mut [u8; 8]) { - bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], out); +fn bc4_pack(v: &Plain, out: &mut [u8]) { + bc4_alpha(v.ep[0], v.ep[1], &v.ix, out); } -fn bc5_pack(v: &Plain, out: &mut [u8; 16]) { +fn bc5_pack(v: &Plain, out: &mut [u8]) { bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], &mut out[..8]); - bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..32], &mut out[8..16]); + bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..], &mut out[8..]); } /// A byte's even and odd bits as two zigzag-coded 4-bit residuals. -#[inline(always)] fn nibbles(b: u8, odd_first: bool) -> [i16; 2] { - let [even, odd] = NIBBLES_EVEN_FIRST[usize::from(b)]; + let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k); + let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); + let (even, odd) = (z(half(b)), z(half(b >> 1))); if odd_first { [odd, even] } else { [even, odd] } } /// Index residual plus reference, both left-aligned to 16 bits at their own /// widths, back to `bits` bits (signed). -#[inline(always)] fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 { let up = |v: i16, b: u8| { if b == 0 || b > 16 { @@ -999,7 +690,6 @@ struct Bits { } impl Bits { - #[inline(always)] fn put(&mut self, value: u64, n: u32) { if n > 0 && self.at < 128 { self.v |= (u128::from(value) & ((1u128 << n) - 1)) << self.at; @@ -1067,104 +757,97 @@ fn bc7_precision(ctrl: u16) -> [u8; 4] { p } -#[inline(always)] -fn bc7_block( - i: usize, - s: &[u8; 32], - block: &mut [u8; 16], - history: &mut [(Bc7Ep, Bc7Ix)], +fn bc7<'a>( + records: impl Iterator, + out: impl Iterator, t: &Tables, - zero: &(Bc7Ep, Bc7Ix), ) -> Result<(), Error> { - let (ep_ref, ix_ref) = references(s, true); - let ctrl = t.ctrl7[usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31)]; - if ctrl == 0 { - return Err(Error("unused BC7 control code")); - } - let mode = usize::from(ctrl & 7); - let subsets = usize::from((ctrl & 0xff) >> 6); - let prec = bc7_precision(ctrl); - let three = subsets == 3; - let or0 = |v: u8| if three { 0 } else { v }; - let if3 = |v: u8| if three { v } else { 0 }; - let stored = [ - [s[4], s[5], s[6], s[7], s[8], s[9], or0(s[10]), or0(s[11])], - [ - s[12], - s[13], - s[14], - s[15], - s[16], - s[17], - or0(s[18]), - or0(s[19]), - ], - [ - s[20], - s[21], - if3(s[10]), - if3(s[11]), - if3(s[18]), - if3(s[19]), - 0, - 0, - ], - ]; - let r = &pick(i, ep_ref, history, &t.bc7, zero).0; - let mut ep = Bc7Ep { - ctrl, - ..Default::default() - }; - // Rows the reference lacks build on its first row. - let common = subsets.min(usize::from((r.ctrl & 0xff) >> 6)); - let columns = if prec[3] > 0 { 8 } else { 6 }; - for c in 0..columns { - let p = prec[c / 2]; - if p == 0 { - continue; - } - let sh = 16 - p; - let mask = 0xffffu16 << sh; - for (row, st) in stored.iter().enumerate().take(subsets) { - let v = st[c]; - let residual = (u16::from(v >> 1) ^ (v & 1).wrapping_neg() as i8 as u16) << sh; - let base = r.rows[if row < common { row } else { 0 }][c] & mask; - ep.rows[row][c] = base.wrapping_add(residual); + let mut history = vec![(Bc7Ep::default(), Bc7Ix::default()); HISTORY]; + let zero = (Bc7Ep::default(), Bc7Ix::default()); + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, true); + let ctrl = t.ctrl7[usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31)]; + if ctrl == 0 { + return Err(Error("unused BC7 control code")); } - } - let bits = BC7_INDEX[mode]; - let rx = &pick(i, ix_ref, history, &t.bc7, zero).1; - let mut ix = Bc7Ix { - bits, - ..Default::default() - }; - for (set, offsets) in [[22usize, 24, 26, 28], [12, 14, 16, 20]] - .into_iter() - .enumerate() - { - let b_set = bits[set]; - if b_set == 0 { - continue; + let mode = usize::from(ctrl & 7); + let subsets = usize::from((ctrl & 0xff) >> 6); + let prec = bc7_precision(ctrl); + let three = subsets == 3; + let or0 = |v: u8| if three { 0 } else { v }; + let if3 = |v: u8| if three { v } else { 0 }; + let stored = [ + [s[4], s[5], s[6], s[7], s[8], s[9], or0(s[10]), or0(s[11])], + [ + s[12], + s[13], + s[14], + s[15], + s[16], + s[17], + or0(s[18]), + or0(s[19]), + ], + [ + s[20], + s[21], + if3(s[10]), + if3(s[11]), + if3(s[18]), + if3(s[19]), + 0, + 0, + ], + ]; + let r = &pick(i, ep_ref, &history, &t.bc7, &zero).0; + let mut ep = Bc7Ep { + ctrl, + ..Default::default() + }; + // Rows the reference lacks build on its first row. + let common = subsets.min(usize::from((r.ctrl & 0xff) >> 6)); + let columns = if prec[3] > 0 { 8 } else { 6 }; + for c in 0..columns { + let p = prec[c / 2]; + if p == 0 { + continue; + } + let mask = 0xffffu16 << (16 - p); + for (row, st) in stored.iter().enumerate().take(subsets) { + let v = st[c]; + let residual = + (u16::from(v >> 1) ^ (v & 1).wrapping_neg() as i8 as u16) << (16 - p); + let base = r.rows[if row < common { row } else { 0 }][c] & mask; + ep.rows[row][c] = base.wrapping_add(residual); + } } - let rb_set = rx.bits[set]; - for (k, o) in offsets.into_iter().enumerate() { - let odd_first = k < 3; - let [v0, v1] = nibbles(s[o], odd_first); - let [v2, v3] = nibbles(s[o + 1], odd_first); - let p0 = 4 * k; - ix.ix[set][p0] = add_index(v0, b_set, rx.ix[set][p0], rb_set); - ix.ix[set][p0 + 1] = add_index(v1, b_set, rx.ix[set][p0 + 1], rb_set); - ix.ix[set][p0 + 2] = add_index(v2, b_set, rx.ix[set][p0 + 2], rb_set); - ix.ix[set][p0 + 3] = add_index(v3, b_set, rx.ix[set][p0 + 3], rb_set); + let bits = BC7_INDEX[mode]; + let rx = &pick(i, ix_ref, &history, &t.bc7, &zero).1; + let mut ix = Bc7Ix { + bits, + ..Default::default() + }; + for (set, offsets) in [[22, 24, 26, 28], [12, 14, 16, 20]].into_iter().enumerate() { + if bits[set] == 0 { + continue; + } + for (k, o) in offsets.into_iter().enumerate() { + for (b, &byte) in s[o..o + 2].iter().enumerate() { + let pair = nibbles(byte, k < 3); + for (h, &v) in pair.iter().enumerate() { + let p = 4 * k + 2 * b + h; + ix.ix[set][p] = add_index(v, bits[set], rx.ix[set][p], rx.bits[set]); + } + } + } } + history[i % HISTORY] = (ep, ix); + bc7_pack(&ep, &ix, prec, block); } - history[i & (HISTORY - 1)] = (ep, ix); - bc7_pack(&ep, &ix, prec, block); Ok(()) } -#[inline(always)] -fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8; 16]) { +fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { let ctrl = ep.ctrl; let mode = ctrl & 7; let subsets = usize::from((ctrl & 0xff) >> 6); @@ -1203,15 +886,15 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8; 16]) { m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)), _ => {} } - let anchor_mask: u16 = match subsets { - 2 => 1 | (1u16 << ANCHOR2[part]), - 3 => 1 | (1u16 << ANCHOR3A[part]) | (1u16 << ANCHOR3B[part]), - _ => 1, + let anchors: &[u8] = match subsets { + 2 => &[0, ANCHOR2[part]], + 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], + _ => &[0], }; let mut indices = |set: usize| { - let bits = u32::from(ix.bits[set]); + let bits = ix.bits[set]; for (p, &v) in ix.ix[set].iter().enumerate() { - let n = bits - u32::from((anchor_mask >> p) & 1); + let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8))); w.put(u64::from(v as u16), n); } }; @@ -1226,7 +909,7 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8; 16]) { } _ => indices(0), } - *out = w.v.to_le_bytes(); + out.copy_from_slice(&w.v.to_le_bytes()); } // BC6H. @@ -1374,99 +1057,107 @@ fn bc6_index_bits(mode: u8) -> u8 { } } -#[inline(always)] -fn bc6_block( - i: usize, - s: &[u8; 32], - block: &mut [u8; 16], - history: &mut [(Bc6Ep, Bc6Ix)], +fn bc6<'a>( + records: impl Iterator, + out: impl Iterator, dictionary: &[(Bc6Ep, Bc6Ix)], - zero: &(Bc6Ep, Bc6Ix), ) -> Result<(), Error> { + let mut history = vec![(Bc6Ep::default(), Bc6Ix::default()); HISTORY]; + let zero = ( + Bc6Ep::default(), + Bc6Ix { + mode: 11, + ..Default::default() + }, + ); let z = |v: u16| (v >> 1) ^ (v & 1).wrapping_neg(); - let wide = |a: u8, b: u8| SPREAD8[usize::from(a)] | (SPREAD8[usize::from(b)] << 1); - let (ep_ref, ix_ref) = references(s, true); - let mode = s[30].wrapping_add(1); - if !(1..=14).contains(&mode) { - return Err(Error("BC6H mode out of range")); - } - let two = mode < 11; - let shift = BC6_BITS[usize::from(mode)].map(|b| 16 - u32::from(b)); - let e0 = [wide(s[4], s[5]), wide(s[6], s[7]), wide(s[8], s[9])].map(z); - let e1 = [wide(s[10], s[11]), wide(s[12], s[13]), wide(s[14], s[15])].map(z); - let (e2, e3) = if two { - ( - [s[16], s[18], s[20]].map(|v| z(v.into())), - [s[17], s[19], s[21]].map(|v| z(v.into())), - ) - } else { - (e0, e1) + let wide = |a: u8, b: u8| { + (0..8).fold(0u16, |acc, k| { + acc | u16::from(a >> k & 1) << (2 * k) | u16::from(b >> k & 1) << (2 * k + 1) + }) }; - let r = &pick(i, ep_ref, history, dictionary, zero).0; - let mut ep = Bc6Ep::default(); - // Endpoint 0 at the base precision, the others per channel; the - // reference is cut by the mask after the sum. - let mask = |sh: u32| 0xffffu16 << sh; - for ((e, &r), res) in ep.e[0].iter_mut().zip(&r.e[0]).zip(e0) { - *e = r.wrapping_add(res << shift[0]) & mask(shift[0]); - } - for (k, res) in [e1, e2, e3] - .iter() - .enumerate() - .take(if two { 3 } else { 1 }) - { - for c in 0..3 { - ep.e[k + 1][c] = - r.e[k + 1][c].wrapping_add(res[c] << shift[1 + c]) & mask(shift[1 + c]); - } - } - if !two { - for c in 0..3 { - ep.e[2][c] = (ep.e[0][c] >> shift[0]) << shift[1]; + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, true); + let mode = s[30].wrapping_add(1); + if !(1..=14).contains(&mode) { + return Err(Error("BC6H mode out of range")); } - ep.e[3] = ep.e[1]; - } - let rx = &pick(i, ix_ref, history, dictionary, zero).1; - let bits = bc6_index_bits(mode); - let ref_bits = bc6_index_bits(rx.mode); - let mut ix = Bc6Ix { - mode, - ..Default::default() - }; - for k in 0..8 { - let [v0, v1] = nibbles(s[22 + k], k < 6); - let p0 = 2 * k; - ix.ix[p0] = add_index(v0, bits, rx.ix[p0], ref_bits); - ix.ix[p0 + 1] = add_index(v1, bits, rx.ix[p0 + 1], ref_bits); - } - history[i & (HISTORY - 1)] = (ep, ix); - // Fields: the working value has its top bit flipped. - let field = |k: usize, c: usize| { - let sh = if k == 0 { shift[0] } else { shift[1 + c] }; - u64::from((ep.e[k][c] ^ 0x8000) >> sh) - }; - let mut w = Bits::default(); - let (code, n) = BC6_CODE[usize::from(mode)]; - w.put(code, n); - let part = s[31] & 31; - for run in BC6_LAYOUT[usize::from(mode)] { - if run.ch == 3 { - w.put(part.into(), 5); + let two = mode < 11; + let shift = BC6_BITS[usize::from(mode)].map(|b| 16 - u32::from(b)); + let e0 = [wide(s[4], s[5]), wide(s[6], s[7]), wide(s[8], s[9])].map(z); + let e1 = [wide(s[10], s[11]), wide(s[12], s[13]), wide(s[14], s[15])].map(z); + let (e2, e3) = if two { + ( + [s[16], s[18], s[20]].map(|v| z(v.into())), + [s[17], s[19], s[21]].map(|v| z(v.into())), + ) } else { - w.put( - field(run.ep.into(), run.ch.into()) >> run.first, - run.len.into(), - ); + (e0, e1) + }; + let r = &pick(i, ep_ref, &history, dictionary, &zero).0; + let mut ep = Bc6Ep::default(); + // Endpoint 0 at the base precision, the others per channel; the + // reference is cut by the mask after the sum. + let mask = |sh: u32| 0xffffu16 << sh; + for ((e, &r), res) in ep.e[0].iter_mut().zip(&r.e[0]).zip(e0) { + *e = r.wrapping_add(res << shift[0]) & mask(shift[0]); } + for (k, res) in [e1, e2, e3] + .iter() + .enumerate() + .take(if two { 3 } else { 1 }) + { + for c in 0..3 { + ep.e[k + 1][c] = + r.e[k + 1][c].wrapping_add(res[c] << shift[1 + c]) & mask(shift[1 + c]); + } + } + if !two { + for c in 0..3 { + ep.e[2][c] = (ep.e[0][c] >> shift[0]) << shift[1]; + } + ep.e[3] = ep.e[1]; + } + let rx = &pick(i, ix_ref, &history, dictionary, &zero).1; + let bits = bc6_index_bits(mode); + let mut ix = Bc6Ix { + mode, + ..Default::default() + }; + for k in 0..8 { + for (h, v) in nibbles(s[22 + k], k < 6).into_iter().enumerate() { + let p = 2 * k + h; + ix.ix[p] = add_index(v, bits, rx.ix[p], bc6_index_bits(rx.mode)); + } + } + history[i % HISTORY] = (ep, ix); + // Fields: the working value has its top bit flipped. + let field = |k: usize, c: usize| { + let sh = if k == 0 { shift[0] } else { shift[1 + c] }; + u64::from((ep.e[k][c] ^ 0x8000) >> sh) + }; + let mut w = Bits::default(); + let (code, n) = BC6_CODE[usize::from(mode)]; + w.put(code, n); + let part = s[31] & 31; + for run in BC6_LAYOUT[usize::from(mode)] { + if run.ch == 3 { + w.put(part.into(), 5); + } else { + w.put( + field(run.ep.into(), run.ch.into()) >> run.first, + run.len.into(), + ); + } + } + let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 }; + for (p, &v) in ix.ix.iter().enumerate() { + let short = p == 0 || p == usize::from(anchor); + let v = (v as u16).wrapping_add(1 << (bits - 1)); + w.put(v.into(), u32::from(bits) - u32::from(short)); + } + block.copy_from_slice(&w.v.to_le_bytes()); } - let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 }; - let bias = 1u16 << (bits - 1); - for (p, &v) in ix.ix.iter().enumerate() { - let short = p == 0 || p == usize::from(anchor); - let v = (v as u16).wrapping_add(bias); - w.put(v.into(), u32::from(bits) - u32::from(short)); - } - *block = w.v.to_le_bytes(); Ok(()) } @@ -1782,11 +1473,11 @@ mod tests { left: 1, ..Default::default() }; - lane.step(&t); + lane.step(&t).unwrap(); let (sym, next) = reference_decode(&t, model, x); assert_eq!( (lane.out, lane.x), - (u16::from(sym), next), + (Some(sym), next), "model {model} x {x:#x}" ); } @@ -1903,71 +1594,15 @@ mod tests { assert!(n > 0); } + /// A dictionary entry stands in for a block the decoder made: a set with + /// 0 index bits holds no indices, and pixel 0 is the anchor (top bit clear). #[test] - fn workspace_reuse_matches_fresh_decode_across_all_formats() { - let t = Tables::parse(&tables()).unwrap(); - let layouts: [(u8, &[u8], usize, usize); 6] = [ - (1, &[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1, 8), - (3, &[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2, 16), - (4, &[7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 1, 8), - (5, &[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2, 16), - (6, &[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2, 16), - (7, &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2, 16), - ]; - let mut ws = Workspace::new(); - // Run twice across all 6 formats with different block counts (including > HISTORY = 256) - // so history buffers are reused across formats and calls without leaking prior state. - for &(bc, widths, per, blk_size) in layouts.iter().chain(layouts.iter()) { - let stride = widths.len() * per; - let blocks = if bc == 1 || bc == 7 { 300 } else { 40 }; - let records: Vec> = (0..blocks) - .map(|i| { - let mut r = vec![0u8; stride]; - for (j, &w) in widths.iter().enumerate() { - let mask = (1u16 << (w + 1)) - 1; - for sub in 0..per { - r[j * per + sub] = (((i * 17 + j * 11 + sub * 5) as u16) & mask) as u8; - } - } - if bc == 6 { - r[30] = (i % 14) as u8; // valid BC6H modes 1..=14 - } else if bc == 7 { - r[30] = 0; // control code 0 -> mode 6 in synthetic tables - r[31] = 0; - } - r - }) - .collect(); - let src = stream(&t, widths, per, &records); - let mut via_ws = vec![0xaa; blocks * blk_size]; - let mut fresh = vec![0x55; blocks * blk_size]; - ws.decode(bc, &src, &mut via_ws, &t).unwrap(); - Workspace::new().decode(bc, &src, &mut fresh, &t).unwrap(); - assert_eq!(via_ws, fresh, "BC{bc} mismatch on workspace reuse"); - // Corrupt input after valid decode must error without poisoning the workspace. - assert!( - ws.decode(bc, &src[..src.len() / 2], &mut via_ws, &t) - .is_err() - ); - } - } - - #[test] - fn bit_lookup_tables_match_reference_bit_ops() { - for a in 0..=15u8 { - for b in 0..=15u8 { - let spread = |v: u8| (0..4).fold(0u8, |acc, k| acc | ((v >> k) & 1) << (2 * k)); - assert_eq!(interleave(a, b), spread(a) | (spread(b) << 1)); - } - } - for b in 0..=255u8 { - let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | ((v >> (2 * k)) & 1) << k); - let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); - let (even, odd) = (z(half(b)), z(half(b >> 1))); - assert_eq!(nibbles(b, false), [even, odd]); - assert_eq!(nibbles(b, true), [odd, even]); - let spread8 = (0..8).fold(0u16, |acc, k| acc | (u16::from((b >> k) & 1) << (2 * k))); - assert_eq!(SPREAD8[usize::from(b)], spread8); + fn bc7_dictionary_indices_line_up() { + let t = Tables::builtin().unwrap(); + for (k, (_, ix)) in t.bc7.iter().enumerate() { + let anchor = 0..1 << (ix.bits[0] - 1); + let ok = (ix.bits[1] != 0 || ix.ix[1] == [0; 16]) && anchor.contains(&ix.ix[0][0]); + assert!(ok, "entry {k}: {:?}", ix.ix); } } } diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index e31bea3..a1f72e4 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -30,8 +30,6 @@ //! Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, //! EXPRESS OR IMPLIED. -use std::sync::OnceLock; - /// A swizzle mode, by its hardware number (addrlib's `ADDR_SW_*` order). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Swizzle(pub u32); @@ -176,14 +174,11 @@ pub struct Layout { /// The first mip in the tail; `mips.len()` without one. pub first_tail_mip: u32, pub mips: Vec, - /// Byte offsets inside a block for each coordinate, per axis. - /// Empty for linear and unsupported modes. - pattern: &'static SwizzlePattern, + /// Byte offsets inside a block of each element coordinate bit, per + /// axis; empty for linear and unsupported modes. + pattern: [Vec; 3], } -type SwizzlePattern = [Vec; 3]; -static EMPTY_PATTERN: SwizzlePattern = [const { Vec::new() }; 3]; - /// Micro tile (256 bytes) patterns by log2 of the element size: for each /// address bit, the element coordinate bit it takes (`x0`, `y1`, `z0`...), /// `--` for the bits inside an element. Thin `S`, thin `D`, thick `S` @@ -252,18 +247,6 @@ fn spread(bits: &[u32]) -> Vec { .collect() } -/// Tables depend only on the micro-tile kind, block size and element size. -/// Texture extents, mip placement and array slices only affect the base -/// address, so layouts with the same key can share these immutable tables. -fn shared_pattern(kind: usize, element_log2: u32, block_log2: u32) -> &'static SwizzlePattern { - // Indexed by MICRO kind, block size (256 B, 4 KiB, 64 KiB), then element size. - static PATTERNS: [[[OnceLock; 5]; 3]; 3] = - [const { [const { [const { OnceLock::new() }; 5] }; 3] }; 3]; - let block_index = ((block_log2 - 8) / 4) as usize; - PATTERNS[kind][block_index][element_log2 as usize] - .get_or_init(|| pattern(kind, element_log2, block_log2).map(|bits| spread(&bits))) -} - const MAX_MIPS: u32 = 16; /// The largest width, height and depth (or array size) accepted, in texels. @@ -339,7 +322,7 @@ impl Layout { alignment: 256, first_tail_mip: d.mips, mips, - pattern: &EMPTY_PATTERN, + pattern: Default::default(), } } @@ -347,18 +330,13 @@ impl Layout { let element_log2 = d.element_bytes.trailing_zeros(); let bpe = u64::from(d.element_bytes); let block_bytes = 1u64 << block_log2; - let thick = - d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display()); + let thick = d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display()); let block = if thick { // ComputeThickBlockDimension let amp = (block_log2 - 10) / 3; let rest = (block_log2 - 10) % 3; let b = BLOCK_1K_3D[element_log2 as usize]; - [ - b[0] << amp, - b[1] << (amp + rest / 2), - b[2] << (amp + u32::from(rest != 0)), - ] + [b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + u32::from(rest != 0))] } else { // ComputeThinBlockDimension let samples_log2 = d.samples.trailing_zeros(); @@ -374,12 +352,7 @@ impl Layout { let mip_depth = |i: u32| if thick { padded_dim(d.depth, i, 1) } else { 1 }; let depth_of = |i: u32| if three_d { dim(d.depth, i, 1) } else { 1 }; let (width, height) = (|i| dim(d.width, i, d.block), |i| dim(d.height, i, d.block)); - let padded = |i| { - ( - padded_dim(d.width, i, d.block), - padded_dim(d.height, i, d.block), - ) - }; + let padded = |i| (padded_dim(d.width, i, d.block), padded_dim(d.height, i, d.block)); let mut mips = Vec::with_capacity(d.mips as usize); let mut first_tail_mip = d.mips; let mut slice_size = 0u64; @@ -394,8 +367,10 @@ impl Layout { offset: 0, tail: None, }); - slice_size = - u64::from(mips[0].pitch) * u64::from(mips[0].rows) * bpe * u64::from(d.samples); + slice_size = u64::from(mips[0].pitch) + * u64::from(mips[0].rows) + * bpe + * u64::from(d.samples); } else { // GetMipTailDim: the largest mip the tail takes. let mut tail_max = block; @@ -515,9 +490,9 @@ impl Layout { } else { usize::from(d.swizzle.display()) }; - shared_pattern(kind, element_log2, block_log2) + pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)) } else { - &EMPTY_PATTERN + Default::default() }; Layout { desc: d, @@ -589,8 +564,7 @@ impl Layout { // offset inside the tail block. let y = y + m.tail.map_or(0, |t| t.y); let blocks = u64::from(y / bh) * u64::from(m.pitch / bw); - (blocks << log2) - + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize]) + (blocks << log2) + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize]) } /// The part of an address that depends on the column. @@ -620,65 +594,9 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk( - tiled.len(), - mip, - slice, - linear.len(), - row_pitch, - depth_pitch, - |t, l, len| { - linear[l..][..len].copy_from_slice(&tiled[t..][..len]); - }, - ) - } - - /// The byte ranges of tiled memory that [`Layout::detile`] reads for - /// mip `mip` of array slice `slice` (3D: every depth slice of the mip, - /// `slice` 0): sorted, disjoint, one per depth slice or slab at most. - /// A mip in the tail gets the part of the tail block its elements span, - /// which other tail mips may share; a write outside every range leaves - /// the subresource's detiled contents as they were. - pub fn extents(&self, mip: u32, slice: u32) -> Result>, Error> { - let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; - let bytes = m.width as usize * self.desc.element_bytes as usize; - let depth_pitch = bytes * m.height as usize; - let mut spans: Vec> = Vec::new(); - let z_of = |linear: usize| linear / depth_pitch; - let mut current: Option<(usize, std::ops::Range)> = None; - self.walk( - self.size as usize, - mip, - slice, - usize::MAX, - bytes, - depth_pitch, - |tiled, linear, len| { - let z = z_of(linear); - let run = tiled as u64..(tiled + len) as u64; - match &mut current { - Some((at, r)) if *at == z => { - r.start = r.start.min(run.start); - r.end = r.end.max(run.end); - } - _ => { - if let Some((_, r)) = current.replace((z, run)) { - spans.push(r); - } - } - } - }, - )?; - spans.extend(current.map(|(_, r)| r)); - spans.sort_by_key(|r| r.start); - let mut merged: Vec> = Vec::with_capacity(spans.len()); - for r in spans { - match merged.last_mut() { - Some(last) if r.start <= last.end => last.end = last.end.max(r.end), - _ => merged.push(r), - } - } - Ok(merged) + self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { + linear[l..][..len].copy_from_slice(&tiled[t..][..len]); + }) } /// The reverse of [`Layout::detile`]: linear rows into tiled memory. @@ -691,17 +609,9 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk( - tiled.len(), - mip, - slice, - linear.len(), - row_pitch, - depth_pitch, - |t, l, len| { - tiled[t..][..len].copy_from_slice(&linear[l..][..len]); - }, - ) + self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { + tiled[t..][..len].copy_from_slice(&linear[l..][..len]); + }) } /// Visits contiguous runs as (tiled byte offset, linear byte offset, length). @@ -890,14 +800,7 @@ impl Texture { 1 }; let mips = match desc.mips { - 0 => { - 32 - desc - .width - .max(desc.height) - .max(depth3d) - .max(1) - .leading_zeros() - } + 0 => 32 - desc.width.max(desc.height).max(depth3d).max(1).leading_zeros(), n => n, }; let plane = |bytes| Desc { @@ -1029,11 +932,7 @@ mod tests { let mut seen = vec![false; l.size as usize]; let mut tiled = vec![0u8; l.size as usize]; let n = d.element_bytes as usize; - let slices = if d.dimension == Dimension::Tex3d { - 1 - } else { - d.depth - }; + let slices = if d.dimension == Dimension::Tex3d { 1 } else { d.depth }; for slice in 0..slices { for mip in 0..d.mips { let m = l.mips[mip as usize]; @@ -1062,96 +961,13 @@ mod tests { seen[at] = true; } } - assert!( - back[base + plane - 11..base + plane] - .iter() - .all(|&b| b == 0xcc) - ); + assert!(back[base + plane - 11..base + plane].iter().all(|&b| b == 0xcc)); } } } } } - /// A subresource's extents hold every element it detiles, and bytes - /// outside them do not change what it detiles to. - #[test] - fn extents_hold_what_a_subresource_detiles() { - let cases = [ - desc(64, 64, 7, 16, Swizzle::SW_64KB_D), - desc(100, 60, 7, 4, Swizzle::SW_64KB_D), - desc(250, 175, 8, 8, Swizzle::SW_4KB_S), - desc(33, 17, 6, 1, Swizzle::SW_4KB_D), - desc(30, 20, 5, 4, Swizzle::LINEAR), - desc(83, 31, 6, 1, Swizzle::SW_256B_S), - Desc { - depth: 3, - ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S) - }, - Desc { - depth: 4, - ..desc(30, 20, 3, 4, Swizzle::LINEAR) - }, - Desc { - dimension: Dimension::Tex3d, - depth: 16, - ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S) - }, - ]; - for d in cases { - let l = Layout::new(&d).unwrap(); - let size = l.size as usize; - let tiled: Vec = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); - let slices = if d.dimension == Dimension::Tex3d { - 1 - } else { - d.depth - }; - for slice in 0..slices { - for mip in 0..d.mips { - let e = l.extents(mip, slice).unwrap(); - assert!(!e.is_empty(), "{d:?} mip {mip} slice {slice}"); - for w in e.windows(2) { - assert!(w[0].end < w[1].start, "{d:?} mip {mip}: {e:?}"); - } - assert!(e.iter().all(|r| r.start < r.end && r.end <= l.size)); - let inside = |at: u64| e.iter().any(|r| r.contains(&at)); - let m = l.mips[mip as usize]; - let n = u64::from(d.element_bytes); - // Outside the tail a 2D mip's extent is its own blocks. - if m.tail.is_none() && d.dimension != Dimension::Tex3d { - let total: u64 = e.iter().map(|r| r.end - r.start).sum(); - let own = u64::from(m.pitch) * u64::from(m.rows) * n; - assert!(total <= own, "{d:?} mip {mip}: {total} > {own}"); - } - for z in 0..m.depth { - for y in 0..m.height { - for x in 0..m.width { - let at = l.offset(mip, x, y, slice + z).unwrap(); - assert!(inside(at) && inside(at + n - 1), "{d:?} mip {mip}"); - } - } - } - let row = m.width as usize * n as usize; - let plane = row * m.height as usize; - let mut before = vec![0; plane * m.depth as usize]; - l.detile(&tiled, mip, slice, &mut before, row, plane) - .unwrap(); - let mut changed = tiled.clone(); - for (i, b) in changed.iter_mut().enumerate() { - if !inside(i as u64) { - *b = !*b; - } - } - let mut after = vec![0; before.len()]; - l.detile(&changed, mip, slice, &mut after, row, plane) - .unwrap(); - assert_eq!(before, after, "{d:?} mip {mip} slice {slice}"); - } - } - } - } - /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12, /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first. @@ -1172,41 +988,6 @@ mod tests { assert_eq!(l.offset(0, 0, 16, 0), Ok(8192)); } - #[test] - fn layouts_share_identical_swizzle_tables() { - for (swizzle, kind, dimension, block_log2) in [ - (Swizzle::SW_256B_S, 0, Dimension::Tex2d, 8), - (Swizzle::SW_256B_D, 1, Dimension::Tex2d, 8), - (Swizzle::SW_4KB_S, 0, Dimension::Tex2d, 12), - (Swizzle::SW_4KB_D, 1, Dimension::Tex2d, 12), - (Swizzle::SW_64KB_S, 0, Dimension::Tex2d, 16), - (Swizzle::SW_64KB_D, 1, Dimension::Tex2d, 16), - (Swizzle::SW_4KB_S, 2, Dimension::Tex3d, 12), - (Swizzle::SW_64KB_S, 2, Dimension::Tex3d, 16), - ] { - for element_log2 in 0..5 { - let d = Desc { - dimension, - depth: 8, - ..desc(128, 96, 7, 1 << element_log2, swizzle) - }; - let first = Layout::new(&d).unwrap(); - let second = Layout::new(&Desc { - width: 32, - height: 24, - mips: 3, - depth: 1, - ..d - }) - .unwrap(); - let expected = pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)); - assert_eq!(first.pattern, &expected); - assert!(std::ptr::eq(first.pattern, second.pattern)); - assert!(std::ptr::eq(first.pattern, first.clone().pattern)); - } - } - } - /// A 256x256 BC7 chain in 64 KiB `D`: one tail block holding mips 1-8, /// then mip 0; mip 1 sits at x = 32 elements, 32 KiB into the tail. #[test] diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs index 589c5ed..e6ca931 100644 --- a/crates/victory-formats/src/xma.rs +++ b/crates/victory-formats/src/xma.rs @@ -151,8 +151,7 @@ fn next_frame(data: &[u8], start: usize, end: usize) -> Option { let mut end = end; if end.is_multiple_of(PACKET_BITS) || (last && end / PACKET_BITS == index) { // The next frame begins in the next packet of this stream. - let next = - (end - 1) / PACKET_BITS + 1 + packet(data, (end - 1) / PACKET_BITS)?.skip as usize; + let next = (end - 1) / PACKET_BITS + 1 + packet(data, (end - 1) / PACKET_BITS)?.skip as usize; let header = packet(data, next)?; end = next * PACKET_BITS + HEADER_BITS + header.first_frame_bit as usize; } @@ -249,20 +248,10 @@ fn codes() -> &'static Codes { scale: pairs(&SCALE, -60), scale_rl: pairs(&SCALE_RL, 0), coef: [ - Vlc::new( - COEF0_SYMS - .iter() - .zip(COEF0_LENS) - .map(|(&s, l)| (s as i32, l)), - ), + Vlc::new(COEF0_SYMS.iter().zip(COEF0_LENS).map(|(&s, l)| (s as i32, l))), pairs(&COEF1, 0), ], - vec4: Vlc::new( - VEC4_SYMS - .iter() - .zip(VEC4_LENS) - .map(|(&s, l)| (s as i32 - 1, l)), - ), + vec4: Vlc::new(VEC4_SYMS.iter().zip(VEC4_LENS).map(|(&s, l)| (s as i32 - 1, l))), vec2: pairs(&VEC2, -1), vec1: pairs(&VEC1, 0), } @@ -768,11 +757,7 @@ impl Decoder { ch.scale_factors = target; if ch.reuse_sf { let from = ch.saved_scale_factors[ch.scale_factor_idx]; - for (sf, &offset) in ch.saved_scale_factors[target] - .iter_mut() - .zip(&sf_offsets) - .take(self.num_bands) - { + for (sf, &offset) in ch.saved_scale_factors[target].iter_mut().zip(&sf_offsets).take(self.num_bands) { *sf = from[offset]; } } @@ -905,11 +890,7 @@ impl Decoder { } quant += 31; } - quant_step += if negative { - -(quant + step) - } else { - quant + step - }; + quant_step += if negative { -(quant + step) } else { quant + step }; } if self.channels_for_cur_subframe == 1 { self.ch[self.channel_indexes[0]].quant_step = quant_step; @@ -952,21 +933,13 @@ impl Decoder { let sf = ch.saved_scale_factors[ch.scale_factors]; for band in 0..self.num_bands { let end = sfb[band + 1].min(subframe_len); - let exp = - ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; + let exp = ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; let quant = 10f32.powf(exp as f32 / 20.0); - for (t, &c) in tmp[sfb[band]..end] - .iter_mut() - .zip(&ch.coeffs[sfb[band]..end]) - { + for (t, &c) in tmp[sfb[band]..end].iter_mut().zip(&ch.coeffs[sfb[band]..end]) { *t = c * quant; } } - imdct_half( - &tmp[..subframe_len], - &mut ch.out[at..at + subframe_len], - scale, - ); + imdct_half(&tmp[..subframe_len], &mut ch.out[at..at + subframe_len], scale); } } else { for i in 0..self.channels_for_cur_subframe { @@ -983,10 +956,7 @@ impl Decoder { start += (winlen - subframe_len) / 2; winlen = subframe_len; } - window_overlap( - &mut ch.out[start..start + winlen], - &windows()[log2(winlen) as usize - 7], - ); + window_overlap(&mut ch.out[start..start + winlen], &windows()[log2(winlen) as usize - 7]); ch.prev_block_len = subframe_len; } @@ -1087,9 +1057,7 @@ mod tests { -(input .iter() .enumerate() - .map(|(k, &x)| { - x as f64 * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos() - }) + .map(|(k, &x)| x as f64 * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos()) .sum::() as f32) }) .collect() @@ -1141,12 +1109,7 @@ mod tests { } } for i in n..5 * n { - assert!( - (out[i] - signal[i]).abs() < 1e-3, - "{i}: {} vs {}", - out[i], - signal[i] - ); + assert!((out[i] - signal[i]).abs() < 1e-3, "{i}: {} vs {}", out[i], signal[i]); } } diff --git a/crates/victory-formats/src/xma/tables.rs b/crates/victory-formats/src/xma/tables.rs index 7a78993..bf8fc43 100644 --- a/crates/victory-formats/src/xma/tables.rs +++ b/crates/victory-formats/src/xma/tables.rs @@ -4,871 +4,407 @@ //! (symbol, code length) in canonical code order. pub(super) const CRITICAL_FREQ: [u16; 28] = [ - 100, 200, 300, 400, 510, 630, 770, 920, 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, 3700, - 4400, 5300, 6400, 7700, 9500, 12000, 15500, 20675, 28575, 41375, 63875, + 100, 200, 300, 400, 510, 630, 770, 920, + 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, + 3700, 4400, 5300, 6400, 7700, 9500, 12000, 15500, + 20675, 28575, 41375, 63875, ]; pub(super) const SCALE: [(u16, u8); 121] = [ - (58, 5), - (64, 6), - (66, 7), - (65, 7), - (62, 5), - (63, 6), - (68, 9), - (69, 10), - (54, 15), - (19, 19), - (20, 19), - (21, 19), - (22, 19), - (23, 19), - (24, 19), - (25, 19), - (26, 19), - (27, 19), - (28, 19), - (29, 19), - (30, 19), - (31, 19), - (32, 19), - (33, 19), - (34, 19), - (17, 19), - (36, 19), - (37, 19), - (38, 19), - (39, 19), - (40, 19), - (41, 19), - (42, 19), - (43, 19), - (44, 19), - (45, 19), - (46, 19), - (47, 19), - (48, 19), - (49, 19), - (50, 19), - (51, 19), - (52, 19), - (15, 19), - (16, 19), - (14, 19), - (13, 19), - (12, 19), - (11, 19), - (10, 19), - (0, 19), - (9, 19), - (8, 19), - (7, 19), - (6, 19), - (5, 19), - (4, 19), - (55, 13), - (70, 13), - (3, 19), - (2, 19), - (1, 19), - (35, 19), - (71, 19), - (72, 19), - (73, 19), - (74, 19), - (75, 19), - (76, 19), - (77, 19), - (78, 19), - (79, 19), - (80, 19), - (81, 19), - (82, 19), - (83, 19), - (84, 19), - (85, 19), - (86, 19), - (87, 19), - (88, 19), - (89, 19), - (90, 19), - (91, 19), - (92, 19), - (93, 19), - (94, 19), - (95, 19), - (96, 19), - (97, 19), - (98, 19), - (99, 19), - (100, 19), - (101, 19), - (102, 19), - (103, 19), - (104, 19), - (105, 19), - (106, 19), - (107, 19), - (108, 19), - (109, 19), - (110, 19), - (111, 19), - (112, 19), - (113, 19), - (114, 19), - (115, 19), - (116, 19), - (117, 19), - (118, 19), - (119, 19), - (120, 19), - (18, 18), - (53, 16), - (56, 11), - (57, 8), - (67, 7), - (61, 3), - (59, 2), + (58, 5), (64, 6), (66, 7), (65, 7), (62, 5), (63, 6), (68, 9), (69, 10), + (54, 15), (19, 19), (20, 19), (21, 19), (22, 19), (23, 19), (24, 19), (25, 19), + (26, 19), (27, 19), (28, 19), (29, 19), (30, 19), (31, 19), (32, 19), (33, 19), + (34, 19), (17, 19), (36, 19), (37, 19), (38, 19), (39, 19), (40, 19), (41, 19), + (42, 19), (43, 19), (44, 19), (45, 19), (46, 19), (47, 19), (48, 19), (49, 19), + (50, 19), (51, 19), (52, 19), (15, 19), (16, 19), (14, 19), (13, 19), (12, 19), + (11, 19), (10, 19), (0, 19), (9, 19), (8, 19), (7, 19), (6, 19), (5, 19), + (4, 19), (55, 13), (70, 13), (3, 19), (2, 19), (1, 19), (35, 19), (71, 19), + (72, 19), (73, 19), (74, 19), (75, 19), (76, 19), (77, 19), (78, 19), (79, 19), + (80, 19), (81, 19), (82, 19), (83, 19), (84, 19), (85, 19), (86, 19), (87, 19), + (88, 19), (89, 19), (90, 19), (91, 19), (92, 19), (93, 19), (94, 19), (95, 19), + (96, 19), (97, 19), (98, 19), (99, 19), (100, 19), (101, 19), (102, 19), (103, 19), + (104, 19), (105, 19), (106, 19), (107, 19), (108, 19), (109, 19), (110, 19), (111, 19), + (112, 19), (113, 19), (114, 19), (115, 19), (116, 19), (117, 19), (118, 19), (119, 19), + (120, 19), (18, 18), (53, 16), (56, 11), (57, 8), (67, 7), (61, 3), (59, 2), (60, 1), ]; pub(super) const SCALE_RL: [(u16, u8); 120] = [ - (103, 7), - (80, 11), - (60, 11), - (18, 10), - (56, 10), - (21, 12), - (90, 12), - (58, 11), - (27, 11), - (69, 12), - (84, 15), - (48, 15), - (86, 14), - (47, 13), - (19, 10), - (32, 9), - (78, 6), - (5, 5), - (28, 4), - (53, 5), - (9, 7), - (31, 8), - (38, 8), - (10, 7), - (88, 11), - (25, 12), - (105, 12), - (118, 11), - (23, 12), - (82, 14), - (98, 16), - (110, 16), - (108, 15), - (93, 13), - (68, 10), - (72, 12), - (97, 12), - (81, 12), - (42, 12), - (64, 8), - (4, 4), - (1, 2), - (7, 6), - (14, 7), - (0, 9), - (55, 9), - (61, 9), - (117, 10), - (24, 12), - (44, 12), - (67, 12), - (70, 16), - (99, 18), - (96, 21), - (95, 21), - (2, 21), - (77, 21), - (52, 21), - (111, 21), - (102, 20), - (101, 17), - (46, 15), - (73, 15), - (109, 15), - (51, 14), - (92, 14), - (30, 7), - (11, 7), - (66, 7), - (15, 8), - (16, 8), - (116, 9), - (65, 9), - (57, 10), - (59, 10), - (115, 9), - (12, 7), - (35, 9), - (17, 9), - (41, 9), - (20, 11), - (91, 11), - (26, 12), - (75, 15), - (45, 15), - (107, 14), - (83, 14), - (100, 15), - (89, 15), - (43, 11), - (62, 9), - (37, 9), - (104, 8), - (6, 5), - (39, 8), - (40, 9), - (34, 9), - (79, 7), - (8, 6), - (63, 6), - (87, 12), - (94, 14), - (49, 14), - (50, 13), - (22, 11), - (119, 10), - (33, 9), - (36, 9), - (113, 11), - (106, 12), - (112, 13), - (71, 15), - (85, 15), - (74, 14), - (76, 10), - (114, 7), - (29, 5), - (54, 6), - (13, 6), - (3, 2), + (103, 7), (80, 11), (60, 11), (18, 10), (56, 10), (21, 12), (90, 12), (58, 11), + (27, 11), (69, 12), (84, 15), (48, 15), (86, 14), (47, 13), (19, 10), (32, 9), + (78, 6), (5, 5), (28, 4), (53, 5), (9, 7), (31, 8), (38, 8), (10, 7), + (88, 11), (25, 12), (105, 12), (118, 11), (23, 12), (82, 14), (98, 16), (110, 16), + (108, 15), (93, 13), (68, 10), (72, 12), (97, 12), (81, 12), (42, 12), (64, 8), + (4, 4), (1, 2), (7, 6), (14, 7), (0, 9), (55, 9), (61, 9), (117, 10), + (24, 12), (44, 12), (67, 12), (70, 16), (99, 18), (96, 21), (95, 21), (2, 21), + (77, 21), (52, 21), (111, 21), (102, 20), (101, 17), (46, 15), (73, 15), (109, 15), + (51, 14), (92, 14), (30, 7), (11, 7), (66, 7), (15, 8), (16, 8), (116, 9), + (65, 9), (57, 10), (59, 10), (115, 9), (12, 7), (35, 9), (17, 9), (41, 9), + (20, 11), (91, 11), (26, 12), (75, 15), (45, 15), (107, 14), (83, 14), (100, 15), + (89, 15), (43, 11), (62, 9), (37, 9), (104, 8), (6, 5), (39, 8), (40, 9), + (34, 9), (79, 7), (8, 6), (63, 6), (87, 12), (94, 14), (49, 14), (50, 13), + (22, 11), (119, 10), (33, 9), (36, 9), (113, 11), (106, 12), (112, 13), (71, 15), + (85, 15), (74, 14), (76, 10), (114, 7), (29, 5), (54, 6), (13, 6), (3, 2), ]; pub(super) const SCALE_RL_RUN: [u8; 120] = [ - 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, - 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, - 4, 5, 6, 7, 8, 9, 10, 0, 1, 0, 1, 0, 1, + 0, 0, 0, 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 0, 1, 2, + 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, + 19, 20, 21, 22, 23, 24, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 0, + 1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 0, 1, 0, 1, 0, 1, ]; pub(super) const SCALE_RL_LEVEL: [u8; 120] = [ - 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, + 0, 0, 1, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 6, + 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 7, 7, 8, 8, 9, 9, ]; pub(super) const COEF0_LENS: [u8; 272] = [ - 2, 9, 14, 14, 13, 12, 13, 14, 15, 15, 12, 10, 10, 10, 13, 14, 15, 15, 12, 11, 13, 14, 14, 13, - 15, 15, 14, 12, 12, 8, 10, 10, 15, 15, 14, 13, 14, 14, 13, 15, 20, 20, 19, 21, 21, 20, 19, 17, - 17, 18, 18, 15, 15, 13, 12, 14, 15, 15, 14, 15, 15, 12, 11, 6, 7, 8, 9, 13, 13, 13, 14, 14, 11, - 10, 7, 8, 14, 14, 14, 14, 12, 13, 13, 12, 12, 12, 11, 9, 13, 14, 14, 12, 11, 11, 11, 9, 8, 7, - 14, 15, 15, 14, 14, 12, 13, 15, 16, 17, 17, 14, 12, 12, 12, 15, 15, 14, 14, 14, 13, 13, 9, 9, - 11, 11, 10, 7, 6, 13, 15, 15, 14, 14, 14, 13, 14, 15, 15, 13, 14, 14, 14, 14, 10, 9, 10, 10, - 11, 11, 10, 8, 9, 13, 14, 14, 12, 11, 14, 15, 15, 13, 12, 14, 14, 14, 14, 13, 14, 14, 3, 5, 8, - 10, 10, 15, 15, 14, 14, 16, 16, 15, 12, 11, 11, 11, 7, 8, 8, 9, 12, 13, 13, 12, 14, 15, 15, 13, - 10, 11, 11, 13, 14, 14, 13, 14, 14, 11, 10, 13, 15, 15, 14, 12, 11, 4, 6, 6, 8, 12, 12, 12, 13, - 13, 12, 13, 13, 14, 14, 13, 13, 13, 9, 7, 9, 11, 14, 14, 13, 14, 14, 13, 10, 8, 7, 5, 9, 12, - 13, 14, 15, 15, 12, 12, 10, 14, 14, 13, 12, 13, 14, 14, 12, 13, 13, 12, 12, 12, 9, 7, 6, 3, 4, - 4, + 2, 9, 14, 14, 13, 12, 13, 14, + 15, 15, 12, 10, 10, 10, 13, 14, + 15, 15, 12, 11, 13, 14, 14, 13, + 15, 15, 14, 12, 12, 8, 10, 10, + 15, 15, 14, 13, 14, 14, 13, 15, + 20, 20, 19, 21, 21, 20, 19, 17, + 17, 18, 18, 15, 15, 13, 12, 14, + 15, 15, 14, 15, 15, 12, 11, 6, + 7, 8, 9, 13, 13, 13, 14, 14, + 11, 10, 7, 8, 14, 14, 14, 14, + 12, 13, 13, 12, 12, 12, 11, 9, + 13, 14, 14, 12, 11, 11, 11, 9, + 8, 7, 14, 15, 15, 14, 14, 12, + 13, 15, 16, 17, 17, 14, 12, 12, + 12, 15, 15, 14, 14, 14, 13, 13, + 9, 9, 11, 11, 10, 7, 6, 13, + 15, 15, 14, 14, 14, 13, 14, 15, + 15, 13, 14, 14, 14, 14, 10, 9, + 10, 10, 11, 11, 10, 8, 9, 13, + 14, 14, 12, 11, 14, 15, 15, 13, + 12, 14, 14, 14, 14, 13, 14, 14, + 3, 5, 8, 10, 10, 15, 15, 14, + 14, 16, 16, 15, 12, 11, 11, 11, + 7, 8, 8, 9, 12, 13, 13, 12, + 14, 15, 15, 13, 10, 11, 11, 13, + 14, 14, 13, 14, 14, 11, 10, 13, + 15, 15, 14, 12, 11, 4, 6, 6, + 8, 12, 12, 12, 13, 13, 12, 13, + 13, 14, 14, 13, 13, 13, 9, 7, + 9, 11, 14, 14, 13, 14, 14, 13, + 10, 8, 7, 5, 9, 12, 13, 14, + 15, 15, 12, 12, 10, 14, 14, 13, + 12, 13, 14, 14, 12, 13, 13, 12, + 12, 12, 9, 7, 6, 3, 4, 4, ]; pub(super) const COEF0_SYMS: [u16; 272] = [ - 2, 25, 111, 94, 69, 58, 87, 93, 136, 135, 59, 37, 34, 36, 82, 182, 120, 138, 195, 45, 168, 216, - 178, 86, 140, 219, 186, 162, 239, 18, 156, 35, 127, 236, 109, 85, 180, 253, 88, 147, 268, 264, - 256, 266, 270, 262, 260, 248, 246, 252, 258, 137, 189, 230, 64, 179, 146, 208, 101, 118, 238, - 163, 46, 9, 153, 0, 26, 247, 169, 76, 202, 131, 194, 38, 13, 19, 132, 106, 191, 97, 65, 198, - 77, 62, 66, 164, 48, 27, 81, 183, 102, 60, 47, 49, 159, 227, 20, 14, 112, 263, 144, 217, 104, - 63, 79, 209, 269, 250, 254, 203, 241, 196, 61, 220, 148, 124, 185, 100, 80, 78, 193, 28, 50, - 235, 41, 1, 10, 171, 226, 150, 103, 114, 115, 170, 105, 211, 149, 249, 108, 188, 107, 255, 231, - 155, 42, 40, 55, 160, 39, 21, 29, 215, 234, 184, 228, 51, 116, 142, 145, 172, 165, 181, 130, - 113, 117, 89, 128, 204, 3, 7, 154, 157, 43, 141, 265, 133, 225, 271, 244, 221, 74, 54, 56, 52, - 15, 222, 22, 30, 83, 199, 173, 73, 123, 210, 143, 175, 44, 53, 237, 174, 139, 134, 110, 218, - 129, 161, 213, 177, 267, 151, 125, 67, 223, 5, 11, 192, 23, 214, 243, 166, 200, 176, 68, 224, - 187, 257, 261, 232, 96, 251, 31, 16, 32, 57, 207, 121, 91, 126, 119, 99, 158, 24, 212, 8, 33, - 70, 92, 205, 240, 242, 75, 197, 233, 259, 190, 98, 71, 201, 122, 206, 72, 90, 95, 84, 167, 245, - 229, 17, 12, 4, 152, 6, + 2, 25, 111, 94, 69, 58, 87, 93, + 136, 135, 59, 37, 34, 36, 82, 182, + 120, 138, 195, 45, 168, 216, 178, 86, + 140, 219, 186, 162, 239, 18, 156, 35, + 127, 236, 109, 85, 180, 253, 88, 147, + 268, 264, 256, 266, 270, 262, 260, 248, + 246, 252, 258, 137, 189, 230, 64, 179, + 146, 208, 101, 118, 238, 163, 46, 9, + 153, 0, 26, 247, 169, 76, 202, 131, + 194, 38, 13, 19, 132, 106, 191, 97, + 65, 198, 77, 62, 66, 164, 48, 27, + 81, 183, 102, 60, 47, 49, 159, 227, + 20, 14, 112, 263, 144, 217, 104, 63, + 79, 209, 269, 250, 254, 203, 241, 196, + 61, 220, 148, 124, 185, 100, 80, 78, + 193, 28, 50, 235, 41, 1, 10, 171, + 226, 150, 103, 114, 115, 170, 105, 211, + 149, 249, 108, 188, 107, 255, 231, 155, + 42, 40, 55, 160, 39, 21, 29, 215, + 234, 184, 228, 51, 116, 142, 145, 172, + 165, 181, 130, 113, 117, 89, 128, 204, + 3, 7, 154, 157, 43, 141, 265, 133, + 225, 271, 244, 221, 74, 54, 56, 52, + 15, 222, 22, 30, 83, 199, 173, 73, + 123, 210, 143, 175, 44, 53, 237, 174, + 139, 134, 110, 218, 129, 161, 213, 177, + 267, 151, 125, 67, 223, 5, 11, 192, + 23, 214, 243, 166, 200, 176, 68, 224, + 187, 257, 261, 232, 96, 251, 31, 16, + 32, 57, 207, 121, 91, 126, 119, 99, + 158, 24, 212, 8, 33, 70, 92, 205, + 240, 242, 75, 197, 233, 259, 190, 98, + 71, 201, 122, 206, 72, 90, 95, 84, + 167, 245, 229, 17, 12, 4, 152, 6, ]; pub(super) const COEF1: [(u16, u8); 244] = [ - (2, 2), - (3, 3), - (102, 3), - (4, 4), - (148, 6), - (134, 9), - (171, 10), - (18, 10), - (11, 8), - (159, 8), - (14, 9), - (156, 14), - (235, 15), - (61, 15), - (38, 13), - (153, 13), - (48, 14), - (49, 14), - (23, 11), - (203, 13), - (208, 19), - (204, 19), - (129, 18), - (94, 17), - (87, 16), - (62, 15), - (174, 15), - (147, 15), - (29, 12), - (191, 12), - (64, 15), - (65, 15), - (146, 14), - (164, 13), - (142, 5), - (132, 4), - (103, 5), - (154, 7), - (165, 9), - (181, 11), - (109, 12), - (30, 12), - (86, 16), - (92, 16), - (239, 15), - (138, 14), - (39, 13), - (50, 14), - (115, 15), - (238, 21), - (228, 21), - (236, 21), - (222, 21), - (216, 20), - (226, 20), - (196, 18), - (192, 17), - (120, 16), - (221, 14), - (51, 14), - (24, 11), - (143, 8), - (7, 6), - (9, 7), - (152, 10), - (136, 12), - (160, 12), - (241, 15), - (66, 15), - (168, 14), - (219, 14), - (113, 14), - (193, 12), - (19, 10), - (173, 10), - (105, 8), - (149, 9), - (15, 9), - (205, 13), - (207, 13), - (125, 17), - (190, 17), - (182, 16), - (68, 15), - (70, 15), - (67, 15), - (137, 13), - (31, 12), - (223, 14), - (116, 15), - (210, 19), - (220, 19), - (198, 18), - (126, 17), - (88, 16), - (41, 13), - (25, 11), - (40, 13), - (73, 15), - (243, 15), - (53, 14), - (195, 12), - (183, 11), - (225, 14), - (52, 14), - (71, 15), - (121, 16), - (89, 16), - (170, 14), - (55, 14), - (69, 15), - (83, 15), - (209, 13), - (108, 11), - (32, 12), - (54, 14), - (122, 16), - (184, 16), - (176, 15), - (42, 13), - (12, 8), - (161, 8), - (6, 5), - (167, 9), - (106, 9), - (20, 10), - (145, 12), - (111, 13), - (43, 13), - (26, 11), - (175, 10), - (107, 10), - (34, 12), - (33, 12), - (197, 12), - (74, 15), - (128, 17), - (232, 20), - (212, 20), - (224, 19), - (202, 18), - (90, 16), - (57, 14), - (227, 14), - (97, 16), - (93, 16), - (140, 15), - (185, 11), - (27, 11), - (16, 9), - (158, 11), - (211, 13), - (56, 14), - (117, 15), - (72, 15), - (166, 13), - (91, 16), - (95, 16), - (80, 15), - (101, 16), - (194, 17), - (127, 17), - (82, 15), - (21, 10), - (144, 10), - (177, 10), - (151, 6), - (10, 7), - (157, 7), - (8, 6), - (5, 4), - (13, 8), - (0, 9), - (213, 13), - (46, 13), - (199, 12), - (35, 12), - (162, 12), - (135, 10), - (169, 9), - (45, 13), - (59, 14), - (114, 14), - (44, 13), - (188, 16), - (186, 16), - (75, 15), - (79, 15), - (118, 15), - (187, 11), - (112, 13), - (139, 14), - (178, 15), - (81, 15), - (110, 12), - (28, 11), - (163, 8), - (133, 6), - (104, 6), - (17, 9), - (22, 10), - (229, 14), - (172, 14), - (217, 13), - (201, 12), - (36, 12), - (218, 20), - (242, 22), - (240, 22), - (234, 21), - (230, 19), - (206, 18), - (200, 18), - (214, 18), - (130, 17), - (131, 17), - (141, 15), - (84, 15), - (76, 15), - (215, 13), - (58, 14), - (231, 14), - (233, 14), - (180, 15), - (77, 15), - (37, 12), - (189, 11), - (179, 10), - (155, 10), - (47, 13), - (96, 16), - (99, 16), - (119, 15), - (63, 14), - (237, 14), - (78, 15), - (85, 15), - (60, 14), - (98, 16), - (100, 16), - (124, 16), - (123, 16), - (150, 11), - (1, 7), + (2, 2), (3, 3), (102, 3), (4, 4), (148, 6), (134, 9), (171, 10), (18, 10), + (11, 8), (159, 8), (14, 9), (156, 14), (235, 15), (61, 15), (38, 13), (153, 13), + (48, 14), (49, 14), (23, 11), (203, 13), (208, 19), (204, 19), (129, 18), (94, 17), + (87, 16), (62, 15), (174, 15), (147, 15), (29, 12), (191, 12), (64, 15), (65, 15), + (146, 14), (164, 13), (142, 5), (132, 4), (103, 5), (154, 7), (165, 9), (181, 11), + (109, 12), (30, 12), (86, 16), (92, 16), (239, 15), (138, 14), (39, 13), (50, 14), + (115, 15), (238, 21), (228, 21), (236, 21), (222, 21), (216, 20), (226, 20), (196, 18), + (192, 17), (120, 16), (221, 14), (51, 14), (24, 11), (143, 8), (7, 6), (9, 7), + (152, 10), (136, 12), (160, 12), (241, 15), (66, 15), (168, 14), (219, 14), (113, 14), + (193, 12), (19, 10), (173, 10), (105, 8), (149, 9), (15, 9), (205, 13), (207, 13), + (125, 17), (190, 17), (182, 16), (68, 15), (70, 15), (67, 15), (137, 13), (31, 12), + (223, 14), (116, 15), (210, 19), (220, 19), (198, 18), (126, 17), (88, 16), (41, 13), + (25, 11), (40, 13), (73, 15), (243, 15), (53, 14), (195, 12), (183, 11), (225, 14), + (52, 14), (71, 15), (121, 16), (89, 16), (170, 14), (55, 14), (69, 15), (83, 15), + (209, 13), (108, 11), (32, 12), (54, 14), (122, 16), (184, 16), (176, 15), (42, 13), + (12, 8), (161, 8), (6, 5), (167, 9), (106, 9), (20, 10), (145, 12), (111, 13), + (43, 13), (26, 11), (175, 10), (107, 10), (34, 12), (33, 12), (197, 12), (74, 15), + (128, 17), (232, 20), (212, 20), (224, 19), (202, 18), (90, 16), (57, 14), (227, 14), + (97, 16), (93, 16), (140, 15), (185, 11), (27, 11), (16, 9), (158, 11), (211, 13), + (56, 14), (117, 15), (72, 15), (166, 13), (91, 16), (95, 16), (80, 15), (101, 16), + (194, 17), (127, 17), (82, 15), (21, 10), (144, 10), (177, 10), (151, 6), (10, 7), + (157, 7), (8, 6), (5, 4), (13, 8), (0, 9), (213, 13), (46, 13), (199, 12), + (35, 12), (162, 12), (135, 10), (169, 9), (45, 13), (59, 14), (114, 14), (44, 13), + (188, 16), (186, 16), (75, 15), (79, 15), (118, 15), (187, 11), (112, 13), (139, 14), + (178, 15), (81, 15), (110, 12), (28, 11), (163, 8), (133, 6), (104, 6), (17, 9), + (22, 10), (229, 14), (172, 14), (217, 13), (201, 12), (36, 12), (218, 20), (242, 22), + (240, 22), (234, 21), (230, 19), (206, 18), (200, 18), (214, 18), (130, 17), (131, 17), + (141, 15), (84, 15), (76, 15), (215, 13), (58, 14), (231, 14), (233, 14), (180, 15), + (77, 15), (37, 12), (189, 11), (179, 10), (155, 10), (47, 13), (96, 16), (99, 16), + (119, 15), (63, 14), (237, 14), (78, 15), (85, 15), (60, 14), (98, 16), (100, 16), + (124, 16), (123, 16), (150, 11), (1, 7), ]; pub(super) const COEF0_RUN: [u16; 272] = [ - 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, - 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, - 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, - 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, - 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 0, 1, 2, 3, 4, 5, 6, - 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, - 31, 32, 33, 34, 35, 36, 37, 38, 39, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, - 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, + 0, 0, 0, 1, 2, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, + 38, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, + 62, 63, 64, 65, 66, 67, 68, 69, + 70, 71, 72, 73, 74, 75, 76, 77, + 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 100, 101, + 102, 103, 104, 105, 106, 107, 108, 109, + 110, 111, 112, 113, 114, 115, 116, 117, + 118, 119, 120, 121, 122, 123, 124, 125, + 126, 127, 128, 129, 130, 131, 132, 133, + 134, 135, 136, 137, 138, 139, 140, 141, + 142, 143, 144, 145, 146, 147, 148, 149, + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 0, 1, + 2, 3, 4, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, ]; pub(super) const COEF0_LEVEL: [f32; 272] = [ - 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, - 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 5.0, 5.0, 6.0, - 6.0, 7.0, 7.0, 8.0, 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, 13.0, 14.0, 14.0, - 15.0, 15.0, 16.0, 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, 21.0, 22.0, 22.0, - 23.0, 23.0, 24.0, 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, + 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, + 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, + 5.0, 5.0, 5.0, 6.0, 6.0, 7.0, 7.0, 8.0, + 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, + 12.0, 13.0, 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, + 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, + 20.0, 21.0, 21.0, 22.0, 22.0, 23.0, 23.0, 24.0, + 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, ]; pub(super) const COEF1_RUN: [u16; 244] = [ - 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, - 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, - 97, 98, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, - 23, 24, 25, 26, 27, 28, 29, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 0, 1, 2, 0, 1, 2, - 0, 1, 2, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, + 0, 0, 0, 1, 2, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, + 38, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, + 62, 63, 64, 65, 66, 67, 68, 69, + 70, 71, 72, 73, 74, 75, 76, 77, + 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 0, 1, + 2, 3, 4, 5, 0, 1, 2, 0, + 1, 2, 0, 1, 2, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 0, 0, ]; pub(super) const COEF1_LEVEL: [f32; 244] = [ - 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, - 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, - 6.0, 6.0, 7.0, 7.0, 7.0, 8.0, 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, 13.0, - 14.0, 14.0, 15.0, 15.0, 16.0, 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, 21.0, - 22.0, 22.0, 23.0, 23.0, 24.0, 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, 28.0, 29.0, 29.0, - 30.0, 30.0, 31.0, 31.0, 32.0, 32.0, 33.0, 33.0, 34.0, 34.0, 35.0, 35.0, 36.0, 36.0, 37.0, 37.0, - 38.0, 38.0, 39.0, 39.0, 40.0, 40.0, 41.0, 41.0, 42.0, 42.0, 43.0, 43.0, 44.0, 44.0, 45.0, 45.0, - 46.0, 46.0, 47.0, 47.0, 48.0, 48.0, 49.0, 49.0, 50.0, 51.0, 52.0, + 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, + 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, + 6.0, 6.0, 7.0, 7.0, 7.0, 8.0, 8.0, 9.0, + 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, + 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, 16.0, 17.0, + 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, + 21.0, 22.0, 22.0, 23.0, 23.0, 24.0, 24.0, 25.0, + 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, 28.0, 29.0, + 29.0, 30.0, 30.0, 31.0, 31.0, 32.0, 32.0, 33.0, + 33.0, 34.0, 34.0, 35.0, 35.0, 36.0, 36.0, 37.0, + 37.0, 38.0, 38.0, 39.0, 39.0, 40.0, 40.0, 41.0, + 41.0, 42.0, 42.0, 43.0, 43.0, 44.0, 44.0, 45.0, + 45.0, 46.0, 46.0, 47.0, 47.0, 48.0, 48.0, 49.0, + 49.0, 50.0, 51.0, 52.0, ]; pub(super) const VEC4_LENS: [u8; 127] = [ - 1, 6, 8, 10, 10, 10, 10, 8, 8, 10, 10, 9, 8, 8, 9, 12, 12, 11, 12, 12, 11, 9, 9, 8, 8, 9, 9, 8, - 8, 9, 9, 12, 12, 12, 14, 14, 13, 11, 11, 9, 8, 9, 9, 11, 11, 10, 9, 8, 6, 6, 6, 6, 6, 6, 11, - 11, 10, 11, 11, 10, 10, 11, 11, 9, 7, 6, 7, 7, 6, 6, 6, 5, 7, 11, 11, 10, 9, 8, 6, 9, 9, 10, - 10, 9, 8, 8, 6, 6, 6, 8, 8, 9, 12, 12, 11, 10, 8, 8, 8, 10, 10, 10, 10, 9, 9, 8, 10, 11, 11, 9, - 8, 8, 8, 9, 9, 10, 11, 12, 12, 9, 9, 9, 8, 8, 7, 7, 7, + 1, 6, 8, 10, 10, 10, 10, 8, + 8, 10, 10, 9, 8, 8, 9, 12, + 12, 11, 12, 12, 11, 9, 9, 8, + 8, 9, 9, 8, 8, 9, 9, 12, + 12, 12, 14, 14, 13, 11, 11, 9, + 8, 9, 9, 11, 11, 10, 9, 8, + 6, 6, 6, 6, 6, 6, 11, 11, + 10, 11, 11, 10, 10, 11, 11, 9, + 7, 6, 7, 7, 6, 6, 6, 5, + 7, 11, 11, 10, 9, 8, 6, 9, + 9, 10, 10, 9, 8, 8, 6, 6, + 6, 8, 8, 9, 12, 12, 11, 10, + 8, 8, 8, 10, 10, 10, 10, 9, + 9, 8, 10, 11, 11, 9, 8, 8, + 8, 9, 9, 10, 11, 12, 12, 9, + 9, 9, 8, 8, 7, 7, 7, ]; pub(super) const VEC4_SYMS: [u16; 127] = [ - 0, 4370, 275, 8195, 4146, 12545, 8225, 290, 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, 5121, - 8961, 321, 1041, 51, 4641, 546, 4610, 530, 513, 8451, 4385, 4130, 33, 8211, 5, 66, 4161, 1281, - 81, 6, 801, 8196, 8481, 8449, 4611, 531, 561, 769, 12290, 8226, 19, 4097, 2, 4369, 274, 4354, - 4114, 12291, 16641, 12305, 49, 12321, 260, 4100, 516, 21, 12546, 8466, 4353, 4371, 4626, 257, - 18, 17, 1, 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, 276, 50, 785, 4116, 8209, 4099, 273, - 4113, 258, 259, 4609, 35, 1026, 1025, 16401, 305, 34, 529, 289, 770, 12289, 4, 4145, 4356, - 12306, 8193, 12801, 261, 16386, 4881, 3, 514, 4129, 545, 306, 36, 4101, 65, 20481, 786, 4401, - 4866, 8721, 291, 8450, 8465, 4115, + 0, 4370, 275, 8195, 4146, 12545, 8225, 290, + 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, + 5121, 8961, 321, 1041, 51, 4641, 546, 4610, + 530, 513, 8451, 4385, 4130, 33, 8211, 5, + 66, 4161, 1281, 81, 6, 801, 8196, 8481, + 8449, 4611, 531, 561, 769, 12290, 8226, 19, + 4097, 2, 4369, 274, 4354, 4114, 12291, 16641, + 12305, 49, 12321, 260, 4100, 516, 21, 12546, + 8466, 4353, 4371, 4626, 257, 18, 17, 1, + 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, + 276, 50, 785, 4116, 8209, 4099, 273, 4113, + 258, 259, 4609, 35, 1026, 1025, 16401, 305, + 34, 529, 289, 770, 12289, 4, 4145, 4356, + 12306, 8193, 12801, 261, 16386, 4881, 3, 514, + 4129, 545, 306, 36, 4101, 65, 20481, 786, + 4401, 4866, 8721, 291, 8450, 8465, 4115, ]; pub(super) const VEC2: [(u16, u8); 137] = [ - (19, 5), - (165, 10), - (211, 11), - (46, 11), - (75, 10), - (177, 11), - (12, 11), - (86, 8), - (83, 7), - (38, 7), - (133, 9), - (178, 10), - (28, 10), - (104, 9), - (73, 9), - (35, 5), - (52, 6), - (113, 9), - (8, 9), - (101, 8), - (69, 7), - (0, 3), - (71, 8), - (119, 9), - (91, 10), - (179, 10), - (114, 8), - (166, 10), - (10, 10), - (44, 10), - (145, 10), - (66, 6), - (21, 6), - (24, 8), - (146, 9), - (26, 9), - (65, 7), - (5, 7), - (226, 11), - (225, 12), - (15, 12), - (180, 10), - (147, 9), - (115, 8), - (40, 8), - (89, 9), - (134, 9), - (84, 7), - (54, 7), - (42, 9), - (60, 10), - (31, 11), - (193, 11), - (181, 10), - (76, 10), - (148, 9), - (37, 6), - (67, 6), - (33, 6), - (3, 6), - (17, 6), - (2, 6), - (102, 8), - (87, 8), - (116, 8), - (56, 8), - (50, 5), - (20, 5), - (120, 9), - (58, 9), - (29, 10), - (194, 10), - (135, 9), - (97, 8), - (7, 8), - (105, 9), - (13, 11), - (241, 12), - (16, 12), - (45, 10), - (149, 9), - (74, 9), - (98, 7), - (23, 7), - (85, 7), - (70, 7), - (195, 10), - (161, 10), - (129, 9), - (72, 8), - (51, 5), - (36, 5), - (117, 8), - (61, 10), - (11, 10), - (162, 9), - (1, 7), - (4, 6), - (49, 6), - (68, 6), - (9, 9), - (27, 9), - (130, 8), - (39, 7), - (53, 6), - (99, 7), - (25, 8), - (150, 9), - (90, 9), - (103, 8), - (163, 9), - (196, 10), - (210, 10), - (136, 9), - (121, 9), - (41, 8), - (131, 8), - (43, 9), - (164, 9), - (118, 8), - (88, 8), - (81, 7), - (6, 7), - (55, 7), - (59, 9), - (30, 10), - (209, 11), - (14, 11), - (151, 9), - (106, 9), - (82, 6), - (22, 6), - (100, 7), - (132, 8), - (57, 8), - (18, 4), + (19, 5), (165, 10), (211, 11), (46, 11), (75, 10), (177, 11), (12, 11), (86, 8), + (83, 7), (38, 7), (133, 9), (178, 10), (28, 10), (104, 9), (73, 9), (35, 5), + (52, 6), (113, 9), (8, 9), (101, 8), (69, 7), (0, 3), (71, 8), (119, 9), + (91, 10), (179, 10), (114, 8), (166, 10), (10, 10), (44, 10), (145, 10), (66, 6), + (21, 6), (24, 8), (146, 9), (26, 9), (65, 7), (5, 7), (226, 11), (225, 12), + (15, 12), (180, 10), (147, 9), (115, 8), (40, 8), (89, 9), (134, 9), (84, 7), + (54, 7), (42, 9), (60, 10), (31, 11), (193, 11), (181, 10), (76, 10), (148, 9), + (37, 6), (67, 6), (33, 6), (3, 6), (17, 6), (2, 6), (102, 8), (87, 8), + (116, 8), (56, 8), (50, 5), (20, 5), (120, 9), (58, 9), (29, 10), (194, 10), + (135, 9), (97, 8), (7, 8), (105, 9), (13, 11), (241, 12), (16, 12), (45, 10), + (149, 9), (74, 9), (98, 7), (23, 7), (85, 7), (70, 7), (195, 10), (161, 10), + (129, 9), (72, 8), (51, 5), (36, 5), (117, 8), (61, 10), (11, 10), (162, 9), + (1, 7), (4, 6), (49, 6), (68, 6), (9, 9), (27, 9), (130, 8), (39, 7), + (53, 6), (99, 7), (25, 8), (150, 9), (90, 9), (103, 8), (163, 9), (196, 10), + (210, 10), (136, 9), (121, 9), (41, 8), (131, 8), (43, 9), (164, 9), (118, 8), + (88, 8), (81, 7), (6, 7), (55, 7), (59, 9), (30, 10), (209, 11), (14, 11), + (151, 9), (106, 9), (82, 6), (22, 6), (100, 7), (132, 8), (57, 8), (18, 4), (34, 4), ]; pub(super) const VEC1: [(u16, u8); 101] = [ - (7, 5), - (32, 8), - (59, 10), - (60, 10), - (83, 11), - (82, 11), - (62, 10), - (33, 8), - (45, 9), - (61, 10), - (84, 11), - (85, 11), - (1, 6), - (13, 5), - (19, 6), - (25, 7), - (34, 8), - (46, 9), - (47, 9), - (14, 5), - (6, 5), - (64, 10), - (87, 11), - (86, 11), - (63, 10), - (88, 11), - (90, 11), - (35, 8), - (26, 7), - (0, 7), - (48, 9), - (65, 10), - (66, 10), - (36, 8), - (15, 5), - (20, 6), - (91, 11), - (89, 11), - (67, 10), - (49, 9), - (50, 9), - (69, 10), - (92, 11), - (93, 11), - (27, 7), - (5, 5), - (37, 8), - (68, 10), - (71, 10), - (51, 9), - (52, 9), - (70, 10), - (94, 11), - (96, 11), - (38, 8), - (21, 6), - (16, 5), - (4, 5), - (28, 7), - (53, 9), - (95, 11), - (97, 11), - (73, 10), - (39, 8), - (29, 7), - (72, 10), - (98, 11), - (99, 11), - (54, 9), - (40, 8), - (22, 6), - (30, 7), - (55, 9), - (74, 10), - (76, 10), - (56, 9), - (75, 10), - (77, 10), - (17, 5), - (3, 5), - (23, 6), - (41, 8), - (57, 9), - (78, 10), - (79, 10), - (31, 7), - (10, 4), - (9, 4), - (100, 5), - (2, 5), - (11, 4), - (8, 4), - (18, 5), - (42, 8), - (58, 9), - (80, 10), - (81, 10), - (43, 8), - (44, 8), - (24, 6), - (12, 4), + (7, 5), (32, 8), (59, 10), (60, 10), (83, 11), (82, 11), (62, 10), (33, 8), + (45, 9), (61, 10), (84, 11), (85, 11), (1, 6), (13, 5), (19, 6), (25, 7), + (34, 8), (46, 9), (47, 9), (14, 5), (6, 5), (64, 10), (87, 11), (86, 11), + (63, 10), (88, 11), (90, 11), (35, 8), (26, 7), (0, 7), (48, 9), (65, 10), + (66, 10), (36, 8), (15, 5), (20, 6), (91, 11), (89, 11), (67, 10), (49, 9), + (50, 9), (69, 10), (92, 11), (93, 11), (27, 7), (5, 5), (37, 8), (68, 10), + (71, 10), (51, 9), (52, 9), (70, 10), (94, 11), (96, 11), (38, 8), (21, 6), + (16, 5), (4, 5), (28, 7), (53, 9), (95, 11), (97, 11), (73, 10), (39, 8), + (29, 7), (72, 10), (98, 11), (99, 11), (54, 9), (40, 8), (22, 6), (30, 7), + (55, 9), (74, 10), (76, 10), (56, 9), (75, 10), (77, 10), (17, 5), (3, 5), + (23, 6), (41, 8), (57, 9), (78, 10), (79, 10), (31, 7), (10, 4), (9, 4), + (100, 5), (2, 5), (11, 4), (8, 4), (18, 5), (42, 8), (58, 9), (80, 10), + (81, 10), (43, 8), (44, 8), (24, 6), (12, 4), ]; + diff --git a/crates/victory-game/Cargo.toml b/crates/victory-game/Cargo.toml index b6239d6..92170b4 100644 --- a/crates/victory-game/Cargo.toml +++ b/crates/victory-game/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "victory-game" -description = "Everything specific to Grand Theft Auto VI: its containers, build identities, patches." +description = "Everything specific to the title: its containers, build identities, patches." version.workspace = true edition.workspace = true rust-version.workspace = true @@ -9,7 +9,7 @@ publish.workspace = true [dependencies] memchr.workspace = true -miniz_oxide.workspace = true +zlib-rs.workspace = true [lints] workspace = true diff --git a/crates/victory-game/src/lib.rs b/crates/victory-game/src/lib.rs index 008bbc8..affa682 100644 --- a/crates/victory-game/src/lib.rs +++ b/crates/victory-game/src/lib.rs @@ -1,11 +1,11 @@ -//! Everything specific to Grand Theft Auto VI: its container formats, build +//! Everything specific to the title: its container formats, build //! identities, and the hooks we place in its code (located by per-build //! offsets or byte-pattern signatures). What may and may not be stored here //! is defined in docs/asset-policy.md. pub mod sgd5; -/// A specific build of the Grand Theft Auto VI executable we know how to run. +/// A specific build of the title executable we know how to run. #[derive(Debug, Clone, Copy)] pub struct KnownBuild { /// Our own label, e.g. "1.0.0 retail". diff --git a/crates/victory-game/src/sgd5.rs b/crates/victory-game/src/sgd5.rs index 3305d72..5605b51 100644 --- a/crates/victory-game/src/sgd5.rs +++ b/crates/victory-game/src/sgd5.rs @@ -8,7 +8,7 @@ //! ``` pub const MAGIC: &[u8; 4] = b"SGD5"; -pub const MARKER: [u8; 4] = 0x000D_DCE7_u32.to_le_bytes(); +const MARKER: [u8; 4] = 0x000D_DCE7_u32.to_le_bytes(); /// Containers are at most a few MiB; refuse to allocate for absurd sizes. const MAX_UNPACKED: usize = 64 << 20; @@ -29,22 +29,56 @@ pub struct Record<'a> { impl Record<'_> { /// The container, or `None` if the stream is corrupt. pub fn unpack(&self) -> Option> { - miniz_oxide::inflate::decompress_to_vec_with_limit(self.packed, self.unpacked_size) - .ok() - .filter(|out| out.len() == self.unpacked_size) + let mut state = zlib_rs::Inflate::new(false, 15); + let mut out = Vec::new(); + let (mut in_pos, mut out_pos) = (0usize, 0usize); + loop { + if out_pos == self.unpacked_size { + let mut extra = [0u8; 1]; + let status = state + .decompress( + &self.packed[in_pos..], + &mut extra, + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + return (status == zlib_rs::Status::StreamEnd + && state.total_out() as usize == self.unpacked_size) + .then_some(out); + } + if out_pos == out.len() { + let next_len = if out.is_empty() { + self.unpacked_size + .min(self.packed.len().saturating_mul(4).max(4096)) + } else { + out.len().saturating_mul(2).min(self.unpacked_size) + }; + out.resize(next_len, 0); + } + let status = state + .decompress( + &self.packed[in_pos..], + &mut out[out_pos..], + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + let next_in = state.total_in() as usize; + let next_out = state.total_out() as usize; + match status { + zlib_rs::Status::StreamEnd => { + out.truncate(next_out); + return (next_out == self.unpacked_size).then_some(out); + } + zlib_rs::Status::Ok if next_in != in_pos || next_out != out_pos => { + in_pos = next_in; + out_pos = next_out; + } + zlib_rs::Status::Ok | zlib_rs::Status::BufError => return None, + } + } } } -/// Record size from the marker onwards. The header starts four bytes -/// before the marker and includes the unpacked size. -pub fn encoded_len(header: &[u8; 16]) -> Option { - let n = u32::from_le_bytes(header[..4].try_into().expect("four bytes")); - let again = u32::from_le_bytes(header[8..12].try_into().expect("four bytes")); - let unpacked = u32::from_le_bytes(header[12..].try_into().expect("four bytes")) as usize; - (header[4..8] == MARKER && n == again && n >= 12 && unpacked <= MAX_UNPACKED) - .then_some(n as usize) -} - /// An SGD5 file, or a file holding one (an archive: records are found by /// their marker, so no index is needed). pub fn is_sgd5(file: &[u8]) -> bool { @@ -56,20 +90,22 @@ pub fn records(file: &[u8]) -> impl Iterator> { memchr::memmem::find_iter(file, &MARKER).filter_map(|at| record(file, at)) } -/// Reads a record at a known marker offset in the supplied slice. -pub fn record(file: &[u8], at: usize) -> Option> { - let header: &[u8; 16] = file - .get(at.checked_sub(4)?..at.checked_add(12)?)? - .try_into() - .ok()?; - let n = encoded_len(header)?; - let unpacked_size = u32::from_le_bytes(header[12..].try_into().expect("four bytes")) as usize; +fn record(file: &[u8], at: usize) -> Option> { + let u32_at = |o: usize| { + file.get(o..o + 4) + .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")) as usize) + }; + let n = u32_at(at.checked_sub(4)?)?; + let unpacked_size = u32_at(at + 8)?; + if u32_at(at + 4)? != n || n < 12 || unpacked_size > MAX_UNPACKED { + return None; + } let nul = at.checked_sub(6)?; Some(Record { offset: at, name: (file[nul] == 0).then(|| name_before(file, nul)).flatten(), kind: file[at - 5], - packed: file.get(at + 12..at.checked_add(n)?)?, + packed: file.get(at + 12..at + n)?, unpacked_size, }) } @@ -91,7 +127,13 @@ mod tests { use super::*; fn record_bytes(name: &str, kind: u8, payload: &[u8]) -> Vec { - let packed = miniz_oxide::deflate::compress_to_vec(payload, 6); + let mut buf = vec![0u8; zlib_rs::compress_bound(payload.len())]; + let config = zlib_rs::DeflateConfig { + window_bits: -15, + ..zlib_rs::DeflateConfig::new(6) + }; + let (packed, rc) = zlib_rs::compress_slice(&mut buf, payload, config); + assert_eq!(rc, zlib_rs::ReturnCode::Ok); let n = (packed.len() + 12) as u32; let mut out = vec![0xF4, 0x01, 0, 0, name.len() as u8 + 1]; out.extend_from_slice(name.as_bytes()); @@ -99,7 +141,7 @@ mod tests { for v in [n, 0x000D_DCE7, n, payload.len() as u32] { out.extend_from_slice(&v.to_le_bytes()); } - out.extend_from_slice(&packed); + out.extend_from_slice(packed); out } @@ -141,4 +183,36 @@ mod tests { let r = records(&file).next().unwrap(); assert_eq!(r.unpack(), None); } + + #[test] + fn handles_empty_and_rejects_mismatched_or_truncated_streams() { + let empty = record_bytes("CS_empty", 0x3c, &[]); + assert_eq!(records(&empty).next().unwrap().unpack(), Some(Vec::new())); + + let payload: Vec = (0..16_384u32) + .map(|i| (i.wrapping_mul(31) ^ (i >> 5)) as u8) + .collect(); + let good = record_bytes("PS_big", 0x32, &payload); + let r = records(&good).next().unwrap(); + assert_eq!(r.unpack(), Some(payload.clone())); + + // Oversized stream (declared unpacked_size smaller than actual output). + let mut smaller = good.clone(); + smaller[r.offset + 8..r.offset + 12] + .copy_from_slice(&((payload.len() - 1) as u32).to_le_bytes()); + assert_eq!(records(&smaller).next().unwrap().unpack(), None); + + // Under-filled stream (declared unpacked_size larger than actual output). + let mut larger = good.clone(); + larger[r.offset + 8..r.offset + 12] + .copy_from_slice(&((payload.len() + 1) as u32).to_le_bytes()); + assert_eq!(records(&larger).next().unwrap().unpack(), None); + + // Truncated raw deflate stream. + let mut truncated = good[..good.len() - 1].to_vec(); + let new_n = (truncated.len() - r.offset) as u32; + truncated[r.offset - 4..r.offset].copy_from_slice(&new_n.to_le_bytes()); + truncated[r.offset + 4..r.offset + 8].copy_from_slice(&new_n.to_le_bytes()); + assert_eq!(records(&truncated).next().unwrap().unpack(), None); + } } diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index 1f7ac7b..d380f3a 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -9,7 +9,7 @@ publish.workspace = true [dependencies] blake3.workspace = true -miniz_oxide.workspace = true +zlib-rs.workspace = true tracing.workspace = true anyhow.workspace = true victory-formats.workspace = true @@ -27,10 +27,9 @@ diagnostics = [] workspace = true [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", - "Win32_Graphics_Direct3D_Dxc", "Win32_Graphics_Direct3D_Fxc", "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", diff --git a/crates/victory-gpu/src/address_map.rs b/crates/victory-gpu/src/address_map.rs deleted file mode 100644 index 794e71f..0000000 --- a/crates/victory-gpu/src/address_map.rs +++ /dev/null @@ -1,195 +0,0 @@ -//! The address map translated shaders read title memory through when they -//! compute its address (a pointer they load, the BVH a ray-tracing pass -//! walks): see `victory_shader::emit::address_map` for its layout. It -//! lists the host copies of title memory made so far ([`crate::shadow`]), -//! each through raw views in dynamic slots of the view heap a list binds. -//! -//! shortcut: every copy is brought up to date (the pages the title wrote -//! since) once per list that binds the map, and what shaders write through -//! it stays in the copies (it is not copied back to title memory: the BVH -//! the title builds on the GPU is only read on the GPU). A list of copies -//! that grows into the thousands makes that refresh the cost to watch. - -use std::sync::Arc; - -use victory_shader::emit::address_map::{ENTRY, HEADER, Range, encode}; - -use crate::descriptor::host::HostHeap; -use crate::host::HostList; -use crate::shadow::Shadow; - -/// The most bytes one raw view holds: D3D12 buffer views have at most 2^27 -/// elements. -const VIEW_BYTES: u64 = 4 << 27; - -/// Pieces of title memory the spans `(start, len)` cover, sorted and not -/// overlapping, each with the span that holds it: where spans overlap, the -/// one starting last (the innermost buffer, as [`crate::shadow::find`] -/// picks) holds the piece. -pub(crate) fn pieces(spans: &[(u64, u64)]) -> Vec<(u64, u64, usize)> { - // (address, whether a span starts there, span): ends before starts. - let mut points: Vec<(u64, bool, usize)> = Vec::with_capacity(2 * spans.len()); - for (i, &(start, len)) in spans.iter().enumerate() { - if len > 0 { - points.push((start, true, i)); - points.push((start.saturating_add(len), false, i)); - } - } - points.sort_unstable(); - let mut active = std::collections::BTreeSet::new(); - let mut out: Vec<(u64, u64, usize)> = Vec::new(); - let mut at = 0; - for (x, starts, i) in points { - if x > at - && let Some(&(_, holder)) = active.iter().next_back() - { - match out.last_mut() { - Some(last) if last.2 == holder && last.0 + last.1 == at => last.1 += x - at, - _ => out.push((at, x - at, holder)), - } - } - if starts { - active.insert((spans[i].0, i)); - } else { - active.remove(&(spans[i].0, i)); - } - at = x; - } - out -} - -/// The map's entries for `pieces` of the spans: each piece cut where its -/// span's views ([`VIEW_BYTES`] each) end, with the view (span, view number -/// within the span) and the piece's offset in that view. -fn entries( - spans: &[(u64, u64)], - pieces: &[(u64, u64, usize)], -) -> Vec<(u64, u32, (usize, u64), u32)> { - let mut out = Vec::new(); - for &(start, len, span) in pieces { - let mut at = start; - let end = start + len; - while at < end { - let rel = at - spans[span].0; - let view = rel / VIEW_BYTES; - let view_end = spans[span].0 + (view + 1) * VIEW_BYTES; - let next = end.min(view_end); - out.push(( - at, - (next - at) as u32, - (span, view), - (rel - view * VIEW_BYTES) as u32, - )); - at = next; - } - } - out -} - -/// The address map for draws of `list` while `heap` is its view heap: its -/// host GPU address, and the dynamic slots its views take (to give back -/// when the list is reset). Each copy is brought up to date when the list -/// is submitted. -pub(crate) fn make(list: &HostList, heap: &HostHeap) -> Option<(u64, (u32, u32))> { - let copies: Vec> = crate::shadow::all(); - let spans: Vec<(u64, u64)> = copies.iter().map(|c| c.span()).collect(); - let pieces = pieces(&spans); - let entries = entries(&spans, &pieces); - let mut views: Vec<(usize, u64)> = entries.iter().map(|e| e.2).collect(); - views.sort_unstable(); - views.dedup(); - let n = views.len() as u32; - let first = if n == 0 { 0 } else { heap.dynamic(n)? }; - for (k, &(span, view)) in views.iter().enumerate() { - let copy = &copies[span]; - let offset = view * VIEW_BYTES; - let bytes = (copy.span().1 - offset).min(VIEW_BYTES).next_multiple_of(4); - heap.raw_uav_at( - first + k as u32, - ©.buffer, - offset / 4, - (bytes / 4) as u32, - ); - } - for c in &copies { - if list.first_use(Arc::as_ptr(c) as usize ^ MAP_KEY) { - let (start, len) = c.span(); - c.refresh(list, start, len); - } - } - let ranges: Vec = entries - .iter() - .map(|&(start, len, view, view_offset)| Range { - start, - len, - view: first + views.binary_search(&view).expect("listed") as u32, - view_offset, - }) - .collect(); - let words = encode(&ranges); - // Room for one entry even when there is none: the shader reads it. - let bytes = u64::from(HEADER) + u64::from(ENTRY) * ranges.len().max(1) as u64; - let (gpu, to) = list.scratch(bytes)?; - // SAFETY: `bytes` of the list's upload memory, which outlives the - // list's run; the words fit. - unsafe { - std::ptr::write_bytes(to, 0, bytes as usize); - std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), to, words.len() * 4); - } - Some((gpu, (first, n))) -} - -/// Keeps the map's refreshes apart from other first uses the list asks -/// about (texture keys are addresses too). -const MAP_KEY: usize = 0x5; - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn inner_buffers_win_and_pieces_do_not_overlap() { - // A heap-sized buffer with two placed inside it, one past its end, - // and an empty one. - let spans = [ - (0x1000, 0x1000), - (0x1200, 0x100), - (0x1800, 0x100), - (0x3000, 0x40), - (0x5000, 0), - ]; - assert_eq!( - pieces(&spans), - [ - (0x1000, 0x200, 0), - (0x1200, 0x100, 1), - (0x1300, 0x500, 0), - (0x1800, 0x100, 2), - (0x1900, 0x700, 0), - (0x3000, 0x40, 3), - ] - ); - } - - #[test] - fn the_same_span_twice_is_one_piece() { - assert_eq!( - pieces(&[(0x100, 0x100), (0x100, 0x100)]), - [(0x100, 0x100, 1)] - ); - } - - #[test] - fn pieces_are_cut_where_views_end() { - let spans = [(0x10, 2 * VIEW_BYTES + 8)]; - let e = entries(&spans, &pieces(&spans)); - assert_eq!( - e, - [ - (0x10, VIEW_BYTES as u32, (0, 0), 0), - (0x10 + VIEW_BYTES, VIEW_BYTES as u32, (0, 1), 0), - (0x10 + 2 * VIEW_BYTES, 8, (0, 2), 0), - ] - ); - } -} diff --git a/crates/victory-gpu/src/breadcrumb.rs b/crates/victory-gpu/src/breadcrumb.rs deleted file mode 100644 index fc7cb63..0000000 --- a/crates/victory-gpu/src/breadcrumb.rs +++ /dev/null @@ -1,180 +0,0 @@ -//! Shader breadcrumbs: after a hung or removed device, which shaders' loops -//! ran away. -//! -//! With `VICTORY_SHADER_BREADCRUMBS=1` in a diagnostics build, translated -//! loops store their iteration counts (the largest any lane reached) in one -//! host buffer (see `victory_shader::emit::breadcrumbs`): `BREADCRUMB_SLOTS` -//! slots of `BREADCRUMB_LOOPS` words, a shader's slot taken from its -//! container's digest. The buffer lives in system memory (a shared buffer), -//! so what the GPU wrote survives a device removal, and is cleared before -//! each submission; the shader reaches it through a UAV in the last slot of -//! every view heap (see `HostHeap::breadcrumb_slot`). When the device is -//! removed the failure report names the stages whose loops counted most. - -use std::collections::BTreeMap; -use std::sync::{Mutex, OnceLock}; - -use victory_shader::emit::{BREADCRUMB_LOOPS, BREADCRUMB_SLOTS}; -use windows::Win32::Graphics::Direct3D12::*; -use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_TYPELESS; - -/// The buffer's size in bytes. -const BYTES: u64 = BREADCRUMB_SLOTS as u64 * BREADCRUMB_LOOPS as u64 * 4; - -/// How many of the slowest loops a report names. -const REPORTED: usize = 5; - -/// Whether breadcrumbs are on (a diagnostics build, the switch set). -pub(crate) fn enabled() -> bool { - victory_shader::emit::breadcrumbs() -} - -/// The buffer and where it is mapped, made on first use. -fn buffer() -> Option<&'static (ID3D12Resource, usize)> { - static BUFFER: OnceLock> = OnceLock::new(); - BUFFER - .get_or_init(|| { - let (buffer, data) = crate::host::host()?.shared_buffer(BYTES)?; - Some((buffer, data as usize)) - }) - .as_ref() -} - -/// The stages by slot, with the pipelines that use them. -fn stages() -> &'static Mutex>> { - static STAGES: Mutex>> = Mutex::new(BTreeMap::new()); - &STAGES -} - -/// Makes the buffer's UAV (a raw view of all of it) at `at`, a view heap's -/// breadcrumb entry. -pub(crate) fn describe(device: &ID3D12Device, at: D3D12_CPU_DESCRIPTOR_HANDLE) { - let Some((buffer, _)) = buffer() else { return }; - let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { - Format: DXGI_FORMAT_R32_TYPELESS, - ViewDimension: D3D12_UAV_DIMENSION_BUFFER, - Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { - Buffer: D3D12_BUFFER_UAV { - NumElements: (BYTES / 4) as u32, - Flags: D3D12_BUFFER_UAV_FLAG_RAW, - ..Default::default() - }, - }, - }; - // SAFETY: a slot inside a live heap and a live buffer. - unsafe { device.CreateUnorderedAccessView(buffer, None, Some(&desc), at) }; -} - -/// Zeroes the counts, before a submission (every one is waited for). -pub(crate) fn clear() { - if let Some(&(_, data)) = enabled().then(buffer).flatten() { - // SAFETY: the buffer's own mapping, no submission running. - unsafe { std::ptr::write_bytes(data as *mut u8, 0, BYTES as usize) }; - } -} - -/// Remembers that `name`'s pipeline uses the shader of `container`. -pub(crate) fn note_stage(container: &[u8], name: &str) { - let Some(digest) = container - .get(4..20) - .and_then(|d| <&[u8; 16]>::try_from(d).ok()) - else { - return; - }; - let mut stages = stages().lock().unwrap_or_else(|e| e.into_inner()); - let names = stages - .entry(victory_shader::emit::breadcrumb_slot(digest)) - .or_default(); - if !names.iter().any(|n| n == name) { - names.push(name.to_owned()); - } -} - -/// The loops that counted most, as report lines (most first): the slot's -/// pipelines, the loop's number and its count. Pure, for testing. -fn summarize(words: &[u32], stages: &BTreeMap>) -> Vec { - let mut loops: Vec<(u32, usize, usize)> = words - .iter() - .enumerate() - .filter(|&(_, &count)| count > 0) - .map(|(i, &count)| { - ( - count, - i / BREADCRUMB_LOOPS as usize, - i % BREADCRUMB_LOOPS as usize, - ) - }) - .collect(); - loops.sort_unstable_by(|a, b| b.cmp(a)); - loops - .into_iter() - .take(REPORTED) - .map(|(count, slot, n)| { - let names = stages - .get(&(slot as u32)) - .map_or_else(|| "a shader not seen".to_owned(), |names| names.join(" | ")); - format!("loop {n} of slot {slot} ran {count} iterations ({names})") - }) - .collect() -} - -/// After a device removal: the loops that counted most in the last -/// submission, for the failure report. `None` with breadcrumbs off or no -/// loop that ran. -pub(crate) fn report() -> Option { - let &(_, data) = enabled().then(buffer).flatten()?; - // SAFETY: the buffer's own mapping, `BYTES` long; the device is gone - // or idle, nothing writes it any more. - let words: Vec = (0..BYTES as usize / 4) - .map(|i| unsafe { (data as *const u32).add(i).read_volatile() }) - .collect(); - let stages = stages().lock().unwrap_or_else(|e| e.into_inner()); - let lines = summarize(&words, &stages); - (!lines.is_empty()).then(|| format!("shader breadcrumbs: {}", lines.join("; "))) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_biggest_counts_are_named_with_their_pipelines() { - let mut words = vec![0u32; (BREADCRUMB_SLOTS * BREADCRUMB_LOOPS) as usize]; - let at = |slot: u32, n: u32| (slot * BREADCRUMB_LOOPS + n) as usize; - words[at(3, 0)] = 17; - words[at(3, 2)] = 1_048_576; - words[at(900, 7)] = 5; - let mut stages = BTreeMap::new(); - stages.insert(3, vec!["pipeline A".to_owned(), "pipeline B".to_owned()]); - let lines = summarize(&words, &stages); - assert_eq!( - lines, - [ - "loop 2 of slot 3 ran 1048576 iterations (pipeline A | pipeline B)", - "loop 0 of slot 3 ran 17 iterations (pipeline A | pipeline B)", - "loop 7 of slot 900 ran 5 iterations (a shader not seen)", - ] - ); - assert!(summarize(&vec![0; words.len()], &stages).is_empty()); - } - - #[test] - fn at_most_the_slowest_few_are_named() { - let words: Vec = (1..=20).collect(); - assert_eq!(summarize(&words, &BTreeMap::new()).len(), REPORTED); - } - - #[test] - fn a_stage_is_found_by_its_containers_digest() { - let mut container = b"DXBC".to_vec(); - container.extend((0..16).map(|b| b + 1)); - container.extend([0; 8]); - note_stage(&container, "test pipeline"); - note_stage(&container, "test pipeline"); - let digest: [u8; 16] = std::array::from_fn(|i| i as u8 + 1); - let slot = victory_shader::emit::breadcrumb_slot(&digest); - assert!(slot < BREADCRUMB_SLOTS); - let stages = stages().lock().unwrap(); - assert_eq!(stages[&slot], ["test pipeline"]); - } -} diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index b8ed90b..1522143 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -20,18 +20,139 @@ pub(crate) fn folder() -> Option<&'static PathBuf> { /// too, and their draws traced at debug level. pub(crate) fn listed(n: u64) -> bool { static LIST: std::sync::OnceLock> = std::sync::OnceLock::new(); - LIST.get_or_init(|| { - let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default(); + let named = LIST + .get_or_init(|| { + let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default(); + list.split(',') + .filter_map(|f| f.trim().parse().ok()) + .collect() + }) + .contains(&n); + // `VICTORY_CAPTURE_WORLD`: also the 2nd and the 6th frame after the first + // one that ran 500 draws or more (a title's first 3D frames: their + // numbers depend on how long the menus were shown), and the 30th and + // the 80th (the title opens with a cutscene made in the + // engine: later shots of it, in case the first is dark by design). + // + // `VICTORY_CAPTURE_WORLD_ALSO` (comma-separated): more frames counted + // from that first one (the title's blue patches show from + // about the 118th frame on, when the window's model has arrived and + // the reflections hold values: none of the four above has them). + static ALSO: std::sync::OnceLock> = std::sync::OnceLock::new(); + let also = ALSO.get_or_init(|| { + let list = std::env::var("VICTORY_CAPTURE_WORLD_ALSO").unwrap_or_default(); list.split(',') .filter_map(|f| f.trim().parse().ok()) .collect() - }) - .contains(&n) + }); + let first = WORLD.load(std::sync::atomic::Ordering::Relaxed); + let after = n.wrapping_sub(first); + named || first != u64::MAX && ([2, 6, 30, 80].contains(&after) || also.contains(&after)) +} + +/// With a capture folder, for the frames [`listed`]: `what` is added to +/// the frame's `frame--ops.txt`, one line per draw, dispatch, copy or +/// drop in the order recorded (the title records on several threads, so +/// lines of different lists interleave; each names its list). The file +/// says which pass writes which target, to find the pass whose output +/// stays empty. +#[cfg(feature = "diagnostics")] +pub(crate) fn op(list: usize, what: impl FnOnce() -> String) { + use std::io::Write; + let frame = crate::queue::presented() + 1; + if !listed(frame) { + // Before the world: the last lines are kept, and written out when + // it starts (`before-world-ops.txt`): what the title drew just + // before (the title shows a title card there, whose text + // did not show). + if world_on() && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX { + // At most 300 lines of a frame: the world's first frame alone + // (thousands of operations, recorded before it is known to be + // the world's) pushed everything before it out. + static IN_FRAME: std::sync::Mutex<(u64, u32)> = std::sync::Mutex::new((0, 0)); + { + let mut in_frame = IN_FRAME.lock().unwrap_or_else(|e| e.into_inner()); + if in_frame.0 != frame { + *in_frame = (frame, 0); + } + in_frame.1 += 1; + if in_frame.1 > 300 { + return; + } + } + let what = what(); + let mut ring = RING.lock().unwrap_or_else(|e| e.into_inner()); + if ring.len() >= RING_LINES { + ring.pop_front(); + } + ring.push_back(format!("frame {frame} list {list:#x} {what}")); + } + return; + } + let Some(folder) = folder() else { + return; + }; + static FILE: std::sync::Mutex> = std::sync::Mutex::new(None); + let what = what(); + let mut file = FILE.lock().unwrap_or_else(|e| e.into_inner()); + if file.as_ref().is_none_or(|f| f.0 != frame) { + let Ok(made) = std::fs::File::create(folder.join(format!("frame-{frame}-ops.txt"))) else { + return; + }; + *file = Some((frame, 0, made)); + } + if let Some((_, n, f)) = file.as_mut() { + *n += 1; + let _ = writeln!(f, "{n} list {list:#x} {what}"); + } +} + +/// The last lines of [`op`] before the world. +#[cfg(feature = "diagnostics")] +static RING: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::VecDeque::new()); +#[cfg(feature = "diagnostics")] +const RING_LINES: usize = 6000; + +/// Whether `VICTORY_CAPTURE_WORLD` is set. +fn world_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CAPTURE_WORLD").is_some()) +} + +/// The first frame that ran 500 draws or more (`VICTORY_CAPTURE_WORLD`). +static WORLD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX); + +/// At the present of `frame`: the draws run on the host so far. +pub(crate) fn frame_drew(frame: u64, drawn: u64) { + use std::sync::atomic::Ordering::Relaxed; + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let before = LAST.swap(drawn, Relaxed); + if world_on() + && drawn.saturating_sub(before) >= 500 + && WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed).is_ok() + { + tracing::info!(frame, "the first frame of 500 draws or more: frames {} and {} are captured", frame + 2, frame + 6); + #[cfg(feature = "diagnostics")] + if let Some(folder) = folder() { + let lines: Vec = std::mem::take(&mut *RING.lock().unwrap_or_else(|e| e.into_inner())).into(); + let _ = std::fs::write(folder.join("before-world-ops.txt"), lines.join(" +")); + } + } } /// Whether frame `n` is saved. pub(crate) fn wanted(n: u64) -> bool { - folder().is_some() && (n.is_power_of_two() || listed(n)) + // Before the world, with `VICTORY_CAPTURE_WORLD`: every 16th frame too + // (small pictures of menus, loading screens and title cards). + let before_world = world_on() && n.is_multiple_of(16) && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX; + // In the world: every 8th frame's picture, a timeline of the opening + // cutscene (its shots do not fall on the same frame numbers from run to + // run, so single frames cannot be compared between runs). + let first = WORLD.load(std::sync::atomic::Ordering::Relaxed); + let in_world = world_on() && first != u64::MAX && n > first && (n - first).is_multiple_of(8); + folder().is_some() && (n.is_power_of_two() || listed(n) || before_world || in_world) } /// Saves 8-bit RGBA or BGRA rows (`pitch` bytes apart) as frame `n`. @@ -63,11 +184,10 @@ fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: header.extend(h.to_be_bytes()); header.extend([8, 2, 0, 0, 0]); // 8-bit RGB chunk(&mut png, b"IHDR", &header); - chunk( - &mut png, - b"IDAT", - &miniz_oxide::deflate::compress_to_vec_zlib(&raw, 3), - ); + let mut compressed = vec![0u8; zlib_rs::compress_bound(raw.len())]; + let (idat, rc) = zlib_rs::compress_slice(&mut compressed, &raw, zlib_rs::DeflateConfig::new(3)); + debug_assert_eq!(rc, zlib_rs::ReturnCode::Ok); + chunk(&mut png, b"IDAT", idat); chunk(&mut png, b"IEND", &[]); let path = folder.join(format!("{name}.png")); match std::fs::write(&path, png) { @@ -224,62 +344,9 @@ fn dump_on() -> bool { *ON.get_or_init(|| folder().is_some() && std::env::var_os("VICTORY_DUMP_TARGETS").is_some()) } -/// `VICTORY_SHOW_TARGET=x-f[-]`: each frame, the `n`th -/// (1-based, default 1) texture of that size and format the frame renders -/// to or writes, in first-use order, is presented instead of the title's -/// frame: a view of an intermediate target (a G-buffer's normals or -/// albedo, say) while the final image is still black. Names as in the -/// `VICTORY_DUMP_TARGETS` files (`frame----x-f`). -fn show_spec() -> Option<(u64, u32, i32, usize)> { - static SPEC: std::sync::OnceLock> = std::sync::OnceLock::new(); - *SPEC.get_or_init(|| { - let v = std::env::var("VICTORY_SHOW_TARGET").ok()?; - let mut parts = v.split('-'); - let (w, h) = parts.next()?.split_once('x')?; - let f = parts.next()?.strip_prefix('f')?.parse().ok()?; - let n = parts.next().map_or(Some(1), |n| n.parse().ok())?; - let spec = (w.parse().ok()?, h.parse().ok()?, f, n.max(1)); - tracing::info!( - ?spec, - "presenting an intermediate target (VICTORY_SHOW_TARGET)" - ); - Some(spec) - }) -} - -/// The frame being built's targets matching [`show_spec`], in order. -static SHOWN: std::sync::Mutex)>> = - std::sync::Mutex::new(Vec::new()); - -/// At a present: the target [`show_spec`] names, if this frame had it, and -/// its host state; the list starts afresh for the next frame. -pub(crate) fn take_shown() -> Option<(std::sync::Arc, u32)> { - use std::sync::atomic::Ordering::Relaxed; - let (.., n) = show_spec()?; - let shown = std::mem::take(&mut *SHOWN.lock().unwrap_or_else(|e| e.into_inner())); - let (_, copy) = shown.into_iter().nth(n - 1)?; - let state = copy.state.load(Relaxed); - Some((copy, state)) -} - /// Notes a title texture the frame being built renders to or writes. pub(crate) fn note_target(resource: crate::object::This) { - if resource.is_null() { - return; - } - if let Some((w, h, f, _)) = show_spec() { - let mut shown = SHOWN.lock().unwrap_or_else(|e| e.into_inner()); - if !shown.iter().any(|&(r, _)| r == resource as usize) - && let Some(copy) = crate::resource::host_copy(resource) - { - // SAFETY: a live resource. - let d = unsafe { copy.texture.GetDesc() }; - if (d.Width, d.Height, d.Format.0) == (w, h, f) && d.SampleDesc.Count == 1 { - shown.push((resource as usize, copy)); - } - } - } - if !dump_on() || !listed(crate::queue::presented() + 1) { + if resource.is_null() || !dump_on() || !listed(crate::queue::presented() + 1) { return; } let mut targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner()); @@ -294,9 +361,7 @@ pub(crate) fn note_target(resource: crate::object::This) { pub(crate) fn dump_targets(frame: u64) { use std::sync::atomic::Ordering::Relaxed; let targets = std::mem::take(&mut *TARGETS.lock().unwrap_or_else(|e| e.into_inner())); - let Some(host) = crate::host::host() else { - return; - }; + let Some(host) = crate::host::host() else { return }; for (i, (resource, copy)) in targets.iter().enumerate() { let texture = ©.texture; // SAFETY: a live resource. @@ -306,15 +371,7 @@ pub(crate) fn dump_targets(frame: u64) { } // Every submission has run; the dump's list moves it there and back. let state = copy.state.load(Relaxed); - dump_one( - host, - texture, - state, - frame, - i, - *resource as crate::object::This, - &d, - ); + dump_one(host, texture, state, frame, i, *resource as crate::object::This, &d); } } @@ -358,9 +415,7 @@ fn dump_one( if let Some((buffer, footprint)) = stencil { stencil_values(&buffer, &footprint, frame, resource); } - let Some((buffer, footprint)) = read else { - return; - }; + let Some((buffer, footprint)) = read else { return }; let f = footprint.Footprint; let mut data = std::ptr::null_mut(); // SAFETY: the copy finished; the mapping spans the footprint's rows. @@ -370,13 +425,27 @@ fn dump_one( } let pitch = f.RowPitch as usize; let rows = std::slice::from_raw_parts(data.cast::(), pitch * f.Height as usize); - if let Some(rgba) = to_rgba( - f.Format.0 as u32, - f.Width as usize, - f.Height as usize, - pitch, - rows, - ) { + // A 24-bit depth plane comes back as 32-bit words: which depth values + // (low 24 bits) and which top bytes it holds, the most common first. + if matches!(d.Format.0, 44..=47) { + let mut depths = std::collections::HashMap::::new(); + let mut tops = std::collections::HashMap::::new(); + for y in 0..f.Height as usize { + for x in 0..f.Width as usize { + let at = y * pitch + x * 4; + let w = u32::from_le_bytes(rows[at..at + 4].try_into().unwrap_or([0; 4])); + *depths.entry(w & 0xff_ffff).or_default() += 1; + *tops.entry(w >> 24).or_default() += 1; + } + } + let most = |m: std::collections::HashMap| { + let mut v: Vec<(u32, u32)> = m.into_iter().collect(); + v.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); + (v.len(), v.into_iter().take(12).collect::>()) + }; + tracing::info!(?resource, depths = ?most(depths), top_bytes = ?most(tops), "24-bit depth plane values (value, texels)"); + } + if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) { let name = format!( "frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}", d.Width, d.Height, d.Format.0 @@ -434,7 +503,7 @@ fn stencil_values( .enumerate() .filter(|v| v.1 != 0) .collect(); - most.sort_by_key(|v| std::cmp::Reverse(v.1)); + most.sort_unstable_by_key(|v| std::cmp::Reverse(v.1)); most.truncate(16); tracing::info!( frame, @@ -451,11 +520,7 @@ fn stencil_values( } fn half(h: u16) -> f32 { - let (sign, exp, man) = ( - (h >> 15) as u32, - ((h >> 10) & 0x1f) as i32, - (h & 0x3ff) as f32, - ); + let (sign, exp, man) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32); let v = match exp { 0 => man * 2f32.powi(-24), 31 => f32::INFINITY, @@ -483,8 +548,7 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option let mut out = Vec::with_capacity(w * h * 4); let px = |x: usize, y: usize, n: usize| &rows[y * pitch + x * n..][..n]; let u16_at = |b: &[u8], i: usize| u16::from_le_bytes([b[2 * i], b[2 * i + 1]]); - let u32_at = - |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4])); + let u32_at = |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4])); // Channel values as floats, then scaled. type Decode = Box [f32; 3]>; let (n, decode): (usize, Decode) = match format { @@ -507,62 +571,23 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option } return Some(out); } - 23..=25 | 89 => ( - 4, - Box::new(move |b| { - let v = u32_at(b, 0); - [ - (v & 0x3ff) as f32, - (v >> 10 & 0x3ff) as f32, - (v >> 20 & 0x3ff) as f32, - ] - }), - ), - 26 => ( - 4, - Box::new(move |b| { - let v = u32_at(b, 0); - [ - small_float(v & 0x7ff, 6), - small_float(v >> 11 & 0x7ff, 6), - small_float(v >> 22, 5), - ] - }), - ), - 9..=10 => ( - 8, - Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))]), - ), - 11..=14 => ( - 8, - Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i)))), - ), - 33..=34 => ( - 4, - Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0]), - ), - 1..=2 => ( - 16, - Box::new(move |b| [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i)))), - ), - 15..=16 => ( - 8, - Box::new(move |b| { - [ - f32::from_bits(u32_at(b, 0)), - f32::from_bits(u32_at(b, 1)), - 0.0, - ] - }), - ), - 35..=38 => ( - 4, - Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0]), - ), - 48..=52 => ( - 2, - Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0]), - ), + 23..=25 | 89 => (4, Box::new(move |b| { + let v = u32_at(b, 0); + [(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32] + })), + 26 => (4, Box::new(move |b| { + let v = u32_at(b, 0); + [small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)] + })), + 9..=10 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])), + 11..=14 => (8, Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i))))), + 33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])), + 1..=2 => (16, Box::new(move |b| { + [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i))) + })), + 15..=16 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)), f32::from_bits(u32_at(b, 1)), 0.0])), + 35..=38 => (4, Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0])), + 48..=52 => (2, Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0])), // Single channels (and depth planes): shown as grey. 39..=43 => (4, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), 19..=22 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), @@ -586,10 +611,7 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option let range = (high - low).max(1e-20); // How much of the target holds anything: a lit scene and one bright // lamp on black have the same highest value. - let above = values - .iter() - .filter(|v| v.iter().any(|c| c.is_finite() && *c > low)) - .count(); + let above = values.iter().filter(|v| v.iter().any(|c| c.is_finite() && *c > low)).count(); let nonzero_percent = above as f32 * 100.0 / values.len().max(1) as f32; tracing::info!(format, low, high, nonzero_percent, "target values"); // Small float colour targets (the 1x1 luminance and exposure targets): @@ -625,12 +647,7 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option } } let nonzero_bits_percent = set as f32 * 100.0 / (w * h).max(1) as f32; - tracing::info!( - format, - nonzero_bits_percent, - packed_high, - "target values as packed light" - ); + tracing::info!(format, nonzero_bits_percent, packed_high, "target values as packed light"); // The same words as plain numbers, by class. Tables of indices and // masks say nothing as floats or as packed light: in the title's // shadow-mask table 0 is a block in full shadow, a word up to 255 @@ -820,20 +837,11 @@ mod tests { fn unorm16_and_xr_bias_targets_decode_as_their_formats() { // Red 0x8000 (a half-float -0), green 0x4000, blue 0. let unorm16 = [0x00, 0x80, 0x00, 0x40, 0, 0, 0xff, 0xff]; - assert_eq!( - super::to_rgba(11, 1, 1, 8, &unorm16), - Some(vec![255, 127, 0, 255]) - ); + assert_eq!(super::to_rgba(11, 1, 1, 8, &unorm16), Some(vec![255, 127, 0, 255])); // Red 0x3ff, green 0x1ff, blue 0, alpha 3. let xr = (0x3ffu32 | 0x1ff << 10 | 3 << 30).to_le_bytes(); - assert_eq!( - super::to_rgba(89, 1, 1, 4, &xr), - Some(vec![255, 127, 0, 255]) - ); + assert_eq!(super::to_rgba(89, 1, 1, 4, &xr), Some(vec![255, 127, 0, 255])); // B8G8R8A8 still swaps to RGBA. - assert_eq!( - super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), - Some(vec![3, 2, 1, 255]) - ); + assert_eq!(super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), Some(vec![3, 2, 1, 255])); } } diff --git a/crates/victory-gpu/src/console.rs b/crates/victory-gpu/src/console.rs index 6070d2d..ab7252c 100644 --- a/crates/victory-gpu/src/console.rs +++ b/crates/victory-gpu/src/console.rs @@ -17,7 +17,7 @@ impl Console { /// advanced configuration; Series S has one range, counted as standard /// (7,776 MiB, the published console-mode figure). // shortcut: later system updates gave Series S titles more (amount not - // published here); Grand Theft Auto VI sizes nothing from this figure + // published here); the title sizes nothing from this figure // (it goes by the device type), so update it if a title does. pub const fn title_memory(self) -> (usize, usize) { match self { diff --git a/crates/victory-gpu/src/copy_pool.rs b/crates/victory-gpu/src/copy_pool.rs deleted file mode 100644 index 769fac6..0000000 --- a/crates/victory-gpu/src/copy_pool.rs +++ /dev/null @@ -1,198 +0,0 @@ -//! A submission's refreshes, copied on several threads. -//! -//! Bringing host copies of title memory up to date is a memory copy, and -//! one thread copies far below what the memory can move. Refreshes inside -//! [`queued`] queue their copies, and [`run`] copies them on a few workers -//! with the submitting thread; it returns once all are done, so what -//! follows sees them all. - -use std::cell::RefCell; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Condvar, Mutex, OnceLock}; - -/// A copy of title memory into host memory: destination, source, bytes. -pub(crate) type Piece = (usize, usize, usize); - -thread_local! { - static QUEUE: RefCell>> = const { RefCell::new(None) }; -} - -/// Runs `f`; the copies [`copy`] is asked for on this thread meanwhile are -/// not made but returned, for [`run`]. -pub(crate) fn queued(f: impl FnOnce() -> R) -> (R, Vec) { - let outer = QUEUE.with(|q| q.replace(Some(Vec::new()))); - let result = f(); - let pieces = QUEUE.with(|q| q.replace(outer)).unwrap_or_default(); - (result, pieces) -} - -/// Copies `len` bytes of title memory at `src` into host memory at `dst` -/// ([`crate::host::copy_mapped`]), or queues the copy inside [`queued`]. -/// The caller must not read the destination before [`run`] then. -pub(crate) fn copy(dst: *mut u8, src: *const u8, len: usize) { - let piece = (dst as usize, src as usize, len); - let queued = QUEUE.with(|q| q.borrow_mut().as_mut().map(|q| q.push(piece)).is_some()); - if !queued { - crate::host::copy_mapped(dst, src, len, false); - } -} - -/// Copies are cut to this size, so that one big copy is shared too. -const PIECE: usize = 1 << 20; -/// Below this many bytes in all, one thread copies (waking the workers -/// costs tens of microseconds; 4 MiB take about 0.4 ms). -const PARALLEL_FROM: usize = 4 << 20; -/// Workers besides the submitting thread. -const WORKERS: usize = 3; - -/// Makes the copies [`queued`] returned, on several threads where they are -/// many bytes; returns once all are made. -pub(crate) fn run(pieces: Vec) { - let total: usize = pieces.iter().map(|p| p.2).sum(); - let Some(pool) = (total >= PARALLEL_FROM).then(pool).flatten() else { - for (dst, src, len) in pieces { - crate::host::copy_mapped(dst as *mut u8, src as *const u8, len, false); - } - return; - }; - let mut cut = Vec::with_capacity(pieces.len() + total / PIECE); - for (dst, src, len) in pieces { - let mut at = 0; - while at < len { - let n = (len - at).min(PIECE); - cut.push((dst + at, src + at, n)); - at += n; - } - } - pool.run(cut); -} - -/// One [`run`]'s pieces, taken by index by whichever thread is free. -struct Job { - pieces: Vec, - next: AtomicUsize, - done: AtomicUsize, -} - -impl Job { - /// Copies pieces until none are left to take. - fn work(&self) { - loop { - let i = self.next.fetch_add(1, Ordering::Relaxed); - let Some(&(dst, src, len)) = self.pieces.get(i) else { - return; - }; - crate::host::copy_mapped(dst as *mut u8, src as *const u8, len, false); - self.done.fetch_add(1, Ordering::Release); - } - } -} - -struct Pool { - /// The current job and its number (workers take each job once). - job: Mutex<(u64, Option>)>, - wake: Condvar, - /// Signalled as workers finish their part of a job. - finished: Condvar, - /// One run at a time. - running: Mutex<()>, -} - -impl Pool { - fn run(&self, pieces: Vec) { - let _one = self.running.lock().unwrap_or_else(|e| e.into_inner()); - let n = pieces.len(); - let job = Arc::new(Job { - pieces, - next: AtomicUsize::new(0), - done: AtomicUsize::new(0), - }); - { - let mut slot = self.job.lock().unwrap_or_else(|e| e.into_inner()); - slot.0 += 1; - slot.1 = Some(job.clone()); - } - self.wake.notify_all(); - job.work(); - let mut slot = self.job.lock().unwrap_or_else(|e| e.into_inner()); - while job.done.load(Ordering::Acquire) < n { - slot = self.finished.wait(slot).unwrap_or_else(|e| e.into_inner()); - } - slot.1 = None; - } - - fn worker(&self) { - let mut seen = 0; - loop { - let job = { - let mut slot = self.job.lock().unwrap_or_else(|e| e.into_inner()); - loop { - if slot.0 != seen - && let Some(job) = &slot.1 - { - seen = slot.0; - break job.clone(); - } - slot = self.wake.wait(slot).unwrap_or_else(|e| e.into_inner()); - } - }; - job.work(); - // Under the lock, so the waiting thread cannot miss it. - let _slot = self.job.lock().unwrap_or_else(|e| e.into_inner()); - self.finished.notify_all(); - } - } -} - -/// The workers, started on first use (None where threads cannot start). -fn pool() -> Option<&'static Pool> { - static POOL: OnceLock> = OnceLock::new(); - *POOL.get_or_init(|| { - let pool: &'static Pool = Box::leak(Box::new(Pool { - job: Mutex::new((0, None)), - wake: Condvar::new(), - finished: Condvar::new(), - running: Mutex::new(()), - })); - let started = (0..WORKERS) - .filter(|i| { - std::thread::Builder::new() - .name(format!("victory refresh {i}")) - .spawn(move || pool.worker()) - .is_ok() - }) - .count(); - (started > 0).then_some(pool) - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Queued copies are made by `run`, one big copy cut into pieces too, - /// each byte where it belongs. - #[test] - fn queued_copies_are_made_together() { - let len = 8 << 20; - let src: Vec = (0..len).map(|i| (i * 7 + i / 4096) as u8).collect(); - let mut dst = vec![0u8; len]; - let (s, d) = (src.as_ptr(), dst.as_mut_ptr()); - let ((), pieces) = queued(|| { - for k in 0..64usize { - let at = (k * 37 % 128) * (64 << 10); - // SAFETY: inside both buffers. - copy(unsafe { d.add(at) }, unsafe { s.add(at) }, 64 << 10); - } - }); - assert_eq!(pieces.len(), 64); - assert!(dst.iter().all(|&b| b == 0)); - run(pieces); - let mut want = vec![0u8; len]; - for k in 0..64usize { - let at = (k * 37 % 128) * (64 << 10); - want[at..at + (64 << 10)].copy_from_slice(&src[at..at + (64 << 10)]); - } - assert!(dst == want); - } -} diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 9f7729e..7f66bd0 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -37,8 +37,98 @@ pub(crate) enum C { TexWatched, TexHashed, TexChanged, + /// Frames presented since the last line (what the line divides by). + Frames, + /// Calls of list methods that record into a host list, and the + /// nanoseconds they took, summed over the title's recording threads. + RecordCalls, + RecordNs, + /// Waiting for host pipelines being made (`pipeline::make`). + PipelineWaitUs, + /// Dynamic descriptor slots: tables asked for, refused (no free run), + /// and the nanoseconds of the searches. + DynamicAsked, + DynamicRefused, + DynamicNs, + /// Marker texts for device-removed data (`HostList::note`). + NoteNs, + /// Ranges given to shaders (steps), their snapshots, and the bytes + /// compared after the submission. + GpuWrites, + SnapshotUs, + BackCompared, + /// Reading around unmapped pages after a failed bulk read. + SparseUs, + /// Guarding view memory (part of the write-watch askings' time). + GuardUs, + /// Bytes copied whole because their memory is neither write-watched + /// nor a view (`Shadow::update_free`). + WholeBytes, + /// Submissions with ranges shaders write (they need the GPU's results + /// before they return). + BackSubmissions, + /// The title's frame waits (`frame::wait`) and the time slept in them, + /// over all its threads. + PaceWaits, + PaceUs, + /// After a present: until the title's first list call and until its + /// first submission; and from its last submission to its next present. + UntilRecordUs, + UntilSubmitUs, + TailUs, + /// Resetting host lists (`HostList::reset`). + ResetNs, + /// What shaders wrote: finding the 64 KiB pieces that differ, how many + /// do, and putting them into title memory. + BackScanUs, + BackDiffer, + BackSyncUs, + /// Texture uploads recorded, and left out as unchanged. + TexUploads, + TexSkipped, + /// Held submissions a present ran although their waits were not met. + Forced, + /// Ranges named through unordered access views by shaders that cannot + /// store to buffers, not given to shaders as written, and their bytes. + GpuWritesLeftOut, + GpuWritesLeftOutBytes, + /// Waits for memory values looked at (`list::ValueWait::met`) and the + /// nanoseconds the looks took, on every thread. + WaitChecks, + WaitCheckNs, + /// Host lists made (`Host::new_list`: for the lists a queue holds and + /// for the parts of lists cut at waits) and the nanoseconds that took. + HostLists, + HostListNs, + /// Parts of held submissions that ran while the part behind them could + /// have run with them (its waits were met already). + PartsTogether, + /// Microseconds of the copies counted in `WholeBytes`. + WholeUs, + /// Submissions by how long the card was waited for (under 2 ms, 2-8, + /// 8-32, longer), and the microseconds waited in each class. + CardUnder2, + Card2To8, + Card8To32, + CardOver32, + CardUnder2Us, + Card2To8Us, + Card8To32Us, + CardOver32Us, + /// Submissions that hand nothing back to the title (no range shaders + /// write, no value written when done), and the microseconds the card + /// was waited for them. + NothingBack, + NothingBackUs, + /// Waits for every earlier shader write recorded into host lists: for + /// the title's barrier groups, for its barriers on buffers, and the + /// indirect commands bounded (each a dispatch of ours between two such + /// waits). + WaitsForGroups, + WaitsForBuffers, + IndirectBounded, } -const COUNTERS: usize = 22; +const COUNTERS: usize = 80; static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; pub(crate) fn add(c: C, n: u64) { @@ -59,6 +149,112 @@ pub(crate) fn mode() -> u8 { type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>; static RANGES: Mutex> = Mutex::new(None); +/// Per range copied whole because its memory is not watched (start, +/// length): copies and microseconds. +static WHOLE: Mutex>> = Mutex::new(None); + +/// `len` bytes at `src`, memory that is not watched, were copied whole in +/// `us`. +pub(crate) fn whole(src: usize, len: usize, us: u64) { + add(C::WholeUs, us); + let mut map = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); + let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); + e.0 += 1; + e.1 += us; +} + +/// The longest wait for the card since the last line: microseconds, and +/// what ran (lists and pipelines). +static LONGEST: Mutex<(u64, String)> = Mutex::new((0, String::new())); + +/// The waits for the card since the last line by what ran (lists and +/// pipelines): how many, and their microseconds. +static WAITS_BY_WORK: Mutex>> = Mutex::new(None); + +/// With `VICTORY_GPU_TIMING`: the commands' time on the card since the last +/// line by what they ran (a pipeline, or the kind of command): how many, +/// their microseconds, and the longest one's. +static COMMANDS_BY_WORK: Mutex>> = Mutex::new(None); + +/// A command took `ms` on the card (timing run). `op` is its note: the +/// kind and size first, then the pipeline in brackets, then what it binds. +pub(crate) fn command_took(op: &str, ms: f64) { + let us = (ms * 1e3) as u64; + let mut by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let e = by.get_or_insert_with(HashMap::new).entry(command_key(op)).or_insert((0, 0, 0)); + e.0 += 1; + e.1 += us; + e.2 = e.2.max(us); +} + +/// What a command's note is summed under: its pipeline (`[compute ...]`, +/// `[mesh ..., pixel ...]`) with the command's first word, or without a +/// pipeline its first two words. +fn command_key(op: &str) -> String { + let head = op.split(" | ").next().unwrap_or(op); + let word = head.split(' ').next().unwrap_or(""); + match (head.find('['), head.find(']')) { + (Some(a), Some(b)) if a < b => format!("{word} {}", &head[a..=b]), + _ => head.split(' ').take(2).collect::>().join(" "), + } +} + +/// The card was waited for `us` for a submission; `what` names it if it is +/// the longest since the last line. +pub(crate) fn card_waited(us: u64, what: impl FnOnce() -> String) { + let (n, t) = match us { + 0..2_000 => (C::CardUnder2, C::CardUnder2Us), + 2_000..8_000 => (C::Card2To8, C::Card2To8Us), + 8_000..32_000 => (C::Card8To32, C::Card8To32Us), + _ => (C::CardOver32, C::CardOver32Us), + }; + add(n, 1); + add(t, us); + // Every submission is named (some forty a frame): the same lists run + // every frame, and the eight longest waits of a line were one list + // eight times. + let text = what(); + { + let mut by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let e = by.get_or_insert_with(HashMap::new).entry(text.clone()).or_insert((0, 0)); + e.0 += 1; + e.1 += us; + } + let mut longest = LONGEST.lock().unwrap_or_else(|e| e.into_inner()); + if us > longest.0 { + *longest = (us, text); + } +} + +/// Whether an experiment on barriers is on (`VICTORY_BARRIER_TEST`): bit 0 +/// for `groups` (the title's barrier groups record no wait for earlier +/// shader writes), bit 1 for `indirect` (the pass that bounds an indirect +/// command runs without its two such waits; its state changes stay), both +/// bits for `both`. For timing only: without the waits a shader may read +/// what another has not finished writing. +pub(crate) fn barrier_test() -> u8 { + static TEST: std::sync::OnceLock = std::sync::OnceLock::new(); + *TEST.get_or_init(|| match std::env::var("VICTORY_BARRIER_TEST").as_deref() { + Ok("groups") => 1, + Ok("indirect") => 2, + Ok("both") => 3, + _ => 0, + }) +} + +/// Per range compared after a submission (start, length): times, and the +/// bytes of it written back to the title. +static COMPARED: Mutex>> = Mutex::new(None); + +/// `len` bytes at `src` were compared after a submission and `written` of +/// them put back into title memory. +pub(crate) fn compared(src: usize, len: usize, written: usize) { + let mut map = COMPARED.lock().unwrap_or_else(|e| e.into_inner()); + let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); + e.0 += 1; + e.1 += written as u64; +} + /// A copy of `len` bytes from `src` (memory type `kind`) took `us`. pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) { let mut map = RANGES.lock().unwrap_or_else(|e| e.into_inner()); @@ -71,6 +267,772 @@ pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) { e.2 += us; } +/// Our own allocations alive now, by size of block (under 4 KiB, to 64 KiB, +/// to 1 MiB, larger): bytes, then blocks. "Our own" is the Rust code of +/// every crate in the process: in diagnostics builds [`Counting`] stands in +/// front of the system's heap. The memory map's "process heap segments" +/// hold the blocks under about half a megabyte of ours, of the graphics +/// runtime and of the driver alike (3.5 GB in run 60's gameplay, growing by +/// some 2 MB a frame, and nothing said whose): this says which part is +/// ours. Bigger blocks are allocations of their own in the map. +static OWN: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + +/// The class of [`OWN`] a block of `size` bytes counts in. +fn block_class(size: usize) -> usize { + match size { + 0..0x1000 => 0, + 0x1000..0x1_0000 => 1, + 0x1_0000..0x10_0000 => 2, + _ => 3, + } +} + +fn own(size: usize, made: bool) { + let class = block_class(size); + if made { + OWN[class].fetch_add(size as u64, Relaxed); + OWN[4 + class].fetch_add(1, Relaxed); + } else { + OWN[class].fetch_sub(size as u64, Relaxed); + OWN[4 + class].fetch_sub(1, Relaxed); + } +} + +/// Our own blocks of [`BIG`] bytes and more alive now: where each is (0: +/// none) and its bytes. The memory map lists the process's big allocations +/// by size without saying whose they are (run 65: one of 544 MB, one of +/// 401 MB, two of 174 MB, two of 115 MB); the sizes here say which of them +/// are ours. +static BIG_AT: [std::sync::atomic::AtomicUsize; 64] = [const { std::sync::atomic::AtomicUsize::new(0) }; 64]; +static BIG_BYTES: [AtomicU64; 64] = [const { AtomicU64::new(0) }; 64]; +const BIG: usize = 32 << 20; + +/// A block of [`BIG`] bytes or more was made at `at`, or released there. +fn big(at: *mut u8, size: usize, made: bool) { + if size < BIG { + return; + } + for (place, bytes) in BIG_AT.iter().zip(&BIG_BYTES) { + if made { + if place.compare_exchange(0, at as usize, Relaxed, Relaxed).is_ok() { + bytes.store(size as u64, Relaxed); + return; + } + } else if place.load(Relaxed) == at as usize { + bytes.store(0, Relaxed); + place.store(0, Relaxed); + return; + } + } +} + +/// The sizes of our own big blocks alive, largest first, in MB. +fn big_blocks() -> String { + let mut sizes: Vec = BIG_BYTES.iter().map(|b| b.load(Relaxed)).filter(|&b| b != 0).collect(); + sizes.sort_unstable_by(|a, b| b.cmp(a)); + let text: Vec = sizes.iter().map(|b| format!("{:.2}", *b as f64 / (1 << 20) as f64)).collect(); + if text.is_empty() { "none".into() } else { text.join(", ") } +} + +/// The system's allocator with every block counted in [`OWN`] (two atomic +/// additions per allocation and per release: diagnostics builds only). +struct Counting; + +// SAFETY: every call goes to the system's allocator unchanged; only +// counters are kept beside it. +unsafe impl std::alloc::GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { + // SAFETY: the caller's contract, passed on. + let at = unsafe { std::alloc::System.alloc(layout) }; + if !at.is_null() { + own(layout.size(), true); + big(at, layout.size(), true); + } + at + } + + unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 { + // SAFETY: the caller's contract, passed on. + let at = unsafe { std::alloc::System.alloc_zeroed(layout) }; + if !at.is_null() { + own(layout.size(), true); + big(at, layout.size(), true); + } + at + } + + unsafe fn dealloc(&self, at: *mut u8, layout: std::alloc::Layout) { + own(layout.size(), false); + big(at, layout.size(), false); + // SAFETY: the caller's contract, passed on. + unsafe { std::alloc::System.dealloc(at, layout) }; + } + + unsafe fn realloc(&self, at: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 { + // SAFETY: the caller's contract, passed on. + let moved = unsafe { std::alloc::System.realloc(at, layout, size) }; + if !moved.is_null() { + own(layout.size(), false); + own(size, true); + big(at, layout.size(), false); + big(moved, size, true); + } + moved + } +} + +#[global_allocator] +static HEAP: Counting = Counting; + +#[cfg(test)] +mod command_tests { + /// Commands are summed by pipeline and first word; those without a + /// pipeline by their first two words. + #[test] + fn commands_are_named_by_their_pipeline() { + use super::command_key; + assert_eq!( + command_key("dispatch 182x1x1 [compute 24f989b98dcb03f0] | 24f989b98dcb03f0: u4=0xa6b080 [heap 341380: x]"), + "dispatch [compute 24f989b98dcb03f0]" + ); + assert_eq!( + command_key("indirect kind 10 max 1 at 0xd9358fce0 [mesh 0750cb2d975c7563, pixel 085d374c5a795549] | t"), + "indirect [mesh 0750cb2d975c7563, pixel 085d374c5a795549]" + ); + assert_eq!(command_key("texture upload 0x271b61c28b0 (2048x2048x1 f99 mips 10) sub 0"), "texture upload"); + assert_eq!(command_key("alias copy of 0x26f66aca780 into 0x26fbdc93890"), "alias copy"); + } +} + +#[cfg(test)] +mod own_tests { + use super::{OWN, block_class}; + use std::sync::atomic::Ordering::Relaxed; + + #[test] + fn blocks_count_in_their_size_class() { + assert_eq!(block_class(0), 0); + assert_eq!(block_class(4095), 0); + assert_eq!(block_class(4096), 1); + assert_eq!(block_class(65535), 1); + assert_eq!(block_class(65536), 2); + assert_eq!(block_class((1 << 20) - 1), 2); + assert_eq!(block_class(1 << 20), 3); + } + + /// A block of 32 MiB or more is listed by its size while it lives. + #[test] + fn big_blocks_are_listed_while_they_live() { + let size = (48usize << 20) + 4096; + let listed = |at: usize| { + super::BIG_AT + .iter() + .zip(&super::BIG_BYTES) + .any(|(place, bytes)| place.load(Relaxed) == at && bytes.load(Relaxed) == size as u64) + }; + let block = vec![0u8; size]; + let at = block.as_ptr() as usize; + assert!(listed(at)); + assert!(super::big_blocks().contains("48.00")); + drop(block); + assert!(!listed(at)); + } + + /// A big block shows in the counters while it lives (other tests + /// allocate small blocks meanwhile: only the big class is looked at, + /// and only for at least this block). + #[test] + fn a_block_is_counted_while_it_lives() { + let block = vec![1u8; 8 << 20]; + assert!(OWN[3].load(Relaxed) >= 8 << 20); + assert!(OWN[7].load(Relaxed) >= 1); + drop(block); + assert!(OWN[7].load(Relaxed) < u64::MAX / 2, "no count below zero"); + } +} + +/// The process's memory in bytes: in physical memory, and committed +/// (private bytes). +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.WorkingSetSize as u64, c.PagefileUsage as u64) +} + +/// The PC's memory in bytes: physical memory free, and what is left to +/// commit. +fn system_memory() -> (u64, u64) { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = size_of::() as u32; + // SAFETY: a sized structure. + unsafe { GlobalMemoryStatusEx(&mut m) }; + (m.ullAvailPhys, m.ullAvailPageFile) +} + +/// Whether the address space is walked for the memory map line +/// ([`log_memory_map`]). On by default (this module is in diagnostics +/// builds only); `VICTORY_MEMORY_MAP=0` leaves the walk out. +fn memory_map() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_MEMORY_MAP").is_none_or(|v| v != "0")) +} + +/// Asks which of the pages in `asked` (address, answer) are in physical +/// memory and adds the bytes each stands for (kind, bytes) to its kind. +fn in_memory(asked: &mut Vec<[usize; 2]>, stands: &mut Vec<(usize, u64)>, present: &mut [u64; 10]) { + use windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: our own process; `asked` holds that many entries of two + // words each, as the call fills them in. + let ok = unsafe { + K32QueryWorkingSetEx(GetCurrentProcess(), asked.as_mut_ptr().cast(), (asked.len() * 16) as u32) + } != 0; + if ok { + for (a, &(kind, bytes)) in asked.iter().zip(stands.iter()) { + // Bit 0 of the answer: the page is in the process's memory. + if a[1] & 1 != 0 { + present[kind] += bytes; + } + } + } + asked.clear(); + stands.clear(); +} + +/// Logs what the process has committed by kind, from a walk of its address +/// space, and how much of each kind is in physical memory (one page in +/// sixteen is asked about). The kinds tell the title's own memory from +/// ours: the title's heaps and page views lie at console addresses (below +/// 1 TiB), everything the host allocates lies far above. Run 30, seen +/// from outside at 18.0 GB private: 4.6 GB the title's heaps, 2.6 GB in +/// 162 segments of the process heap, 2.7 GB in 707 allocations of 4 MiB +/// (windows of title memory), 0.46 GB the pipeline library's file; mapped +/// and so not private: 6.2 GB the title's page pool, 2.0 GB the driver's +/// shader cache file. +/// shortcut: the walk takes about 0.6 s on a thread of its own, and a +/// query of a region of gigabytes holds up other threads' memory calls +/// for its length (89 ms for the 6.2 GB pool), so it runs with every +/// sixth memory line only. +fn log_memory_map() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_FREE, MEM_IMAGE, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_WRITECOMBINE, + VirtualQuery, + }; + const KINDS: [&str; 10] = [ + "the title's heaps (private, console addresses)", + "views of the title's pages (mapped, console addresses)", + "the title's page pool (mapped, 1 GB and more)", + "process heap segments (private, 15.8 MB each)", + "windows of title memory and other 4 MiB allocations", + "write-combined (buffers shared with the card)", + "other private allocations of 1 MB and more", + "other private allocations under 1 MB", + "files and other mappings at host addresses", + "programs and libraries", + ]; + /// Console addresses lie below this. + const HOST: usize = 1 << 40; + /// One page asked about stands for this much. + const STEP: usize = 64 << 10; + let started = std::time::Instant::now(); + // Allocation, start, bytes, committed, type, protection. + type Region = (usize, usize, usize, bool, u32, u32); + let mut regions: Vec = Vec::new(); + let mut at = 0usize; + loop { + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + if unsafe { VirtualQuery(at as *const _, &mut m, size_of_val(&m)) } == 0 { + break; + } + if m.State != MEM_FREE { + regions.push(( + m.AllocationBase as usize, + m.BaseAddress as usize, + m.RegionSize, + m.State == MEM_COMMIT, + m.Type, + m.Protect, + )); + } + let next = (m.BaseAddress as usize).saturating_add(m.RegionSize); + if next <= at { + break; + } + at = next; + } + // Each allocation's whole size, reserved parts included. + let mut whole: HashMap = HashMap::new(); + for r in ®ions { + *whole.entry(r.0).or_default() += r.2; + } + let kind = |r: &Region| -> usize { + let size = whole.get(&r.0).copied().unwrap_or(0); + let console = r.0 < HOST; + if r.4 == MEM_IMAGE { + 9 + } else if r.4 == MEM_MAPPED { + match (console, size >= 1 << 30) { + (false, _) => 8, + (true, true) => 2, + (true, false) => 1, + } + } else if console { + 0 + } else if size == 0xfd_0000 { + 3 + } else if size == 4 << 20 { + 4 + } else if r.5 & PAGE_WRITECOMBINE != 0 { + 5 + } else if size >= 1 << 20 { + 6 + } else { + 7 + } + }; + let mut committed = [0u64; 10]; + let mut present = [0u64; 10]; + let mut asked: Vec<[usize; 2]> = Vec::with_capacity(4096); + let mut stands: Vec<(usize, u64)> = Vec::with_capacity(4096); + for r in regions.iter().filter(|r| r.3) { + let k = kind(r); + committed[k] += r.2 as u64; + let mut offset = 0; + while offset < r.2 { + asked.push([r.1 + offset, 0]); + stands.push((k, STEP.min(r.2 - offset) as u64)); + if asked.len() == 4096 { + in_memory(&mut asked, &mut stands, &mut present); + } + offset += STEP; + } + } + if !asked.is_empty() { + in_memory(&mut asked, &mut stands, &mut present); + } + let text: Vec = (0..KINDS.len()) + .filter(|&k| committed[k] > 0) + .map(|k| format!("{} {} MB ({} MB in memory)", KINDS[k], committed[k] >> 20, present[k] >> 20)) + .collect(); + tracing::info!( + "memory map ({} regions, {} ms): {}", + regions.len(), + started.elapsed().as_millis(), + text.join("; ") + ); + // The private allocations the kinds above leave as "other" (and the + // write-combined ones), grouped by their size: the sizes name their + // owners (the pipeline library's file to the byte, a snapshot buffer + // of a title heap's size, the driver's blocks). Committed bytes by + // allocation first, then allocations by (kind, whole size). + let mut by_allocation: HashMap = HashMap::new(); + for r in regions.iter().filter(|r| r.3) { + let k = kind(r); + if k == 5 || k == 6 { + by_allocation.entry(r.0).or_insert((k, 0)).1 += r.2 as u64; + } + } + let mut groups: HashMap<(usize, usize), (u64, u64)> = HashMap::new(); + for (base, &(k, bytes)) in &by_allocation { + let group = groups.entry((k, whole.get(base).copied().unwrap_or(0))).or_default(); + group.0 += 1; + group.1 += bytes; + } + let mut groups: Vec<((usize, usize), (u64, u64))> = groups.into_iter().collect(); + groups.sort_unstable_by_key(|g| std::cmp::Reverse(g.1.1)); + let biggest: Vec = groups + .iter() + .take(20) + .map(|&((k, size), (n, bytes))| { + format!( + "{n} of {:.2} MB{}: {} MB", + size as f64 / (1 << 20) as f64, + if k == 5 { " write-combined" } else { "" }, + bytes >> 20 + ) + }) + .collect(); + tracing::info!( + "memory map, other private allocations by size, the {} biggest groups of {} (committed): {}", + biggest.len(), + groups.len(), + biggest.join("; ") + ); +} + +/// Logs where the memory is: the process and the PC, then what this crate +/// holds by kind (alive now), then the host buffers made since the start. +fn log_memory() { + use std::sync::atomic::Ordering::Relaxed; + let mb = |v: u64| v as f64 / (1 << 20) as f64; + let (working, private) = process_memory(); + let (free, left) = system_memory(); + let copies = crate::shadow::memory(); + let staged = crate::texture::memory(); + let textures = [0, 1].map(|i| crate::resource::HOST_TEXTURES[i].load(Relaxed)); + let made: Vec = crate::host::MADE.iter().map(|m| m.load(Relaxed)).collect(); + let windows = crate::shadow::windows(); + let stagings = crate::texture::let_go(); + let census = crate::resource::census(); + let kinds: Vec = crate::resource::KINDS.iter().map(|k| k.load(Relaxed)).collect(); + let card = crate::host::host() + .and_then(|h| h.video_memory()) + .unwrap_or_default(); + // Everything the system says of the two memory groups, beside the + // budget and use the lines below print. + if let Some(h) = crate::host::host() { + h.log_video_memory("with the memory line"); + } + // What else holds memory: the map, on a thread of its own, with every + // sixth line; and what the shader table and the pipeline library keep. + static LINES: AtomicU64 = AtomicU64::new(0); + static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if memory_map() && LINES.fetch_add(1, Relaxed) % 6 == 5 && !WALKING.swap(true, Relaxed) { + let walk = std::thread::Builder::new().name("victory-memory-map".into()).spawn(|| { + log_memory_map(); + WALKING.store(false, Relaxed); + }); + if walk.is_err() { + WALKING.store(false, Relaxed); + } + } + let kept = crate::pipeline::kept(); + tracing::info!( + "memory kept beside the lines below: {} shader containers {:.0} MB, {} translations \ + {:.0} MB; the pipeline library's file {:.0} MB (its last save wrote {:.0} MB)", + kept[0], + mb(kept[1]), + kept[2], + mb(kept[3]), + mb(kept[4]), + mb(kept[5]), + ); + tracing::info!( + "memory of textures: {} title textures have no host copy yet ({:.0} MB of title memory); \ + host copies the host renders to or writes: {} alive {:.0} MB; host copies the title \ + fills: {} alive {:.0} MB ({} of them placed), {} let go {:.0} MB and {} made again \ + {:.0} MB since the start; {} host copies made in all; passes that made none for lack of \ + room: {}; the card: {:.0} MB in use of a budget of {:.0} MB, {:.0} MB of the PC's memory \ + shared with it in use", + census[2], + mb(census[3]), + census[0], + mb(census[1]), + census[4], + mb(census[5]), + census[6], + kinds[2], + mb(kinds[3]), + kinds[4], + mb(kinds[5]), + kinds[6], + crate::draw::HEAP_TEXTURES_FULL.load(Relaxed), + mb(card[1]), + mb(card[0]), + mb(card[3]), + ); + tracing::info!( + "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \ + {:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \ + asked for in each", + windows[0], + mb(windows[1]), + stagings[0], + mb(stagings[1]), + mb(windows[2]), + ); + tracing::info!( + "memory: {:.0} MB private ({:.0} MB of it in memory; the PC has {:.0} MB free and {:.0} MB \ + left to commit); host copies of title memory: {} alive {:.0} MB, of them {} windows \ + outside buffers {:.0} MB; snapshot buffers kept: {} reserving {:.0} MB; staging of \ + textures: {} alive {:.0} MB, {} kept by their texture; host textures: {} alive {:.0} MB, \ + {} placed in title memory; made so far: {} upload buffers {:.0} MB, {} shared buffers \ + {:.0} MB, {} card buffers {:.0} MB", + mb(private), + mb(working), + mb(free), + mb(left), + copies[0], + mb(copies[1]), + copies[2], + mb(copies[3]), + copies[4], + mb(copies[5]), + staged[0], + mb(staged[1]), + staged[2], + textures[0], + mb(textures[1]), + crate::resource::placed_textures(), + made[0], + mb(made[1]), + made[2], + mb(made[3]), + made[4], + mb(made[5]), + ); + tracing::info!( + "memory, placed textures: {} of them were asked for again with other filler words in their description (one resource and host copy each since the filler left the key; VICTORY_PLACED_FILLER=1 keeps it)", + crate::resource::placed_filler_twins() + ); + // What the line above leaves open: what is alive of the buffers "made + // so far", what the windows hold and what holds them, and what our own + // code has allocated. + let alive: Vec = crate::host::ALIVE.iter().map(|a| a.load(Relaxed)).collect(); + let window = crate::shadow::window_use(); + let views = crate::descriptor::views_kept(); + let own: Vec = OWN.iter().map(|o| o.load(Relaxed)).collect(); + tracing::info!( + "memory, what holds it: {} host lists alive; their scratch memory: {} chunks {:.0} MB, of them {} chunks {:.0} MB spare ({} taken from the spare ones so far); their other upload buffers: {} alive {:.0} MB; windows outside buffers (grid {} KiB): {:.0} MB of their pages ever copied, {} shown by descriptor slots {:.0} MB, {} held by lists or the pass over the heap {:.0} MB, {} asked for without a length {:.0} MB; buffer views of the heap whose slot showed another copy than the one brought up to date: {}; distinct views kept: {} ({} free) {:.0} MB; our own allocations: {:.0} MB in {} blocks (under 4 KiB {:.0} MB in {}, to 64 KiB {:.0} MB in {}, to 1 MiB {:.0} MB in {}, larger {:.0} MB in {})", + alive[0], + alive[1], + mb(alive[2]), + alive[3], + mb(alive[4]), + alive[5], + alive[6], + mb(alive[7]), + window[7] >> 10, + mb(window[0]), + window[1], + mb(window[2]), + window[3], + mb(window[4]), + window[5], + mb(window[6]), + crate::draw::HEAP_VIEWS_ELSEWHERE.load(Relaxed), + views[0], + views[1], + mb(views[2]), + mb(own[..4].iter().sum()), + own[4..].iter().sum::(), + mb(own[0]), + own[4], + mb(own[1]), + own[5], + mb(own[2]), + own[6], + mb(own[3]), + own[7], + ); + // Round 2: what the view table still holds and what goes around it, + // what host lists cost, the card's share that is the layer's own or + // the title's no more, and which big blocks are ours. + let lists: Vec = crate::host::LISTS.iter().map(|l| l.load(Relaxed)).collect(); + tracing::info!( + "memory, more: views named whole in their records since the start: {} constant buffer \ + views, {} views of placed memory; of the view table's entries {} are constant buffer \ + views and {} views of placed memory; shapes of placed views kept: {}; host lists: {} \ + made by the host, {} preludes made for them, private bytes grew {:.0} MB while \ + lists were made; twins of depth textures: {:.0} MB; host copies of \ + placed textures whose title memory is not mapped any more (estimate): {:.0} MB, of \ + them still shown by a descriptor slot {:.0} MB; the pipeline library's mapped file \ + let go from memory so far: {:.0} MB; our own blocks of 32 MB and more, in MB: {}", + views[6], + views[7], + views[3], + views[4], + views[5], + lists[0], + lists[1], + lists[2] as i64 as f64 / (1 << 20) as f64, + mb(census[7]), + mb(census[8]), + mb(census[9]), + mb(kept[6]), + big_blocks(), + ); + // Round 3: whether windows hold the same memory more than once (they + // can, once they are cut finer than 4 MiB), and how many host lists + // the title made and never used. + tracing::info!( + "memory, windows: the {:.0} MB of windows lie over {:.0} MB of title memory (the rest is \ + memory that is in more than one window, and is copied once for each); host lists never \ + reset since they were made: {}", + mb(copies[3]), + mb(crate::shadow::window_cover()), + lists[3], + ); +} + +/// Microseconds since the first call. +fn now_us() -> u64 { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 +} + +/// When the last frame was presented and when the last submission returned +/// ([`now_us`]), and whether a list call and a submission followed that +/// present yet. +static PRESENTED_AT: AtomicU64 = AtomicU64::new(0); +static SUBMITTED_AT: AtomicU64 = AtomicU64::new(0); +static RECORDED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); +static SUBMITTED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + +/// What a thread that submits did between its submissions and in them +/// (microseconds; list calls in nanoseconds). +#[derive(Default, Clone, Copy)] +struct Submitter { + submissions: u64, + /// From a submission's return to the next one's call: wall time, of it + /// the thread running (user, kernel), and inside our list calls. + between: u64, + between_user: u64, + between_kernel: u64, + between_ours: u64, + /// Waiting for the submission lock; running inside submissions. + lock: u64, + inside_user: u64, + inside_kernel: u64, +} + +/// By thread: the submitting threads, and list-call time (nanoseconds, +/// calls) of every recording thread. +static SUBMITTERS: Mutex> = Mutex::new(Vec::new()); +static RECORDERS: Mutex> = Mutex::new(Vec::new()); + +thread_local! { + /// This thread's last submission: when it returned ([`now_us`]) and the + /// thread's processor time then (user, kernel). + static LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// The thread's processor time when its running submission was called. + static ENTERED: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; + /// List-call nanoseconds of this thread since its last submission. + static OURS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// List-call time not yet added to `RECORDERS` (nanoseconds, calls). + static UNSENT: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; +} + +fn thread_id() -> u32 { + // SAFETY: a plain query. + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } +} + +fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 { + (u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime)) / 10 +} + +/// This thread's processor time so far (user, kernel), in microseconds. +fn thread_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own thread and four valid out pointers. + unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +/// The process's processor time so far (user, kernel), in microseconds. +fn process_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own process and four valid out pointers. + unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +fn submitter(all: &mut Vec<(u32, Submitter)>, id: u32) -> &mut Submitter { + let at = match all.iter().position(|s| s.0 == id) { + Some(at) => at, + None => { + all.push((id, Submitter::default())); + all.len() - 1 + } + }; + &mut all[at].1 +} + +/// A list call on this thread that began at `started` has returned. +pub(crate) fn recorded(started: std::time::Instant) { + let ns = started.elapsed().as_nanos() as u64; + add(C::RecordCalls, 1); + add(C::RecordNs, ns); + if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) { + let began = now_us().saturating_sub(ns / 1000); + add(C::UntilRecordUs, began.saturating_sub(PRESENTED_AT.load(Relaxed))); + } + OURS.with(|o| o.set(o.get() + ns)); + let (unsent, calls) = UNSENT.with(|u| u.get()); + let (unsent, calls) = (unsent + ns, calls + 1); + // By thread, a couple of milliseconds at a time. + if unsent < 2_000_000 { + UNSENT.with(|u| u.set((unsent, calls))); + return; + } + UNSENT.with(|u| u.set((0, 0))); + let id = thread_id(); + let mut all = RECORDERS.lock().unwrap_or_else(|e| e.into_inner()); + match all.iter_mut().find(|r| r.0 == id) { + Some(r) => (r.1, r.2) = (r.1 + unsent, r.2 + calls), + None => all.push((id, unsent, calls)), + } +} + +/// A submission is called on this thread (before it waits for the +/// submission lock). +pub(crate) fn submission_begins() { + let now = now_us(); + if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) { + add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed))); + } + let (user, kernel) = thread_times(); + ENTERED.with(|e| e.set((user, kernel))); + let ours = OURS.with(|o| o.replace(0)); + if let Some((left, u, k)) = LEFT.with(|l| l.get()) { + let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()); + let s = submitter(&mut all, thread_id()); + s.between += now.saturating_sub(left); + s.between_user += user.saturating_sub(u); + s.between_kernel += kernel.saturating_sub(k); + s.between_ours += ours; + } +} + +/// The submission returns; it waited `lock` microseconds for the +/// submission lock. +pub(crate) fn submission_ends(lock: u64) { + let now = now_us(); + SUBMITTED_AT.store(now, Relaxed); + let (user, kernel) = thread_times(); + let (u, k) = ENTERED.with(|e| e.get()); + LEFT.with(|l| l.set(Some((now, user, kernel)))); + OURS.with(|o| o.set(0)); + let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()); + let s = submitter(&mut all, thread_id()); + s.submissions += 1; + s.lock += lock; + s.inside_user += user.saturating_sub(u); + s.inside_kernel += kernel.saturating_sub(k); +} + +/// The title calls its present (before our own copy to the window runs). +pub(crate) fn present_begins() { + add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed))); +} + +/// A frame was presented. +pub(crate) fn presented() { + add(C::Frames, 1); + PRESENTED_AT.store(now_us(), Relaxed); + RECORDED_SINCE.store(false, Relaxed); + SUBMITTED_SINCE.store(false, Relaxed); +} + fn page_faults() -> u64 { use windows_sys::Win32::System::ProcessStatus::{ K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, @@ -85,9 +1047,14 @@ fn page_faults() -> u64 { u64::from(c.PageFaultCount) } -/// Logs the counters per frame over `frames` frames, and the ranges that -/// took most bytes. +/// Logs the counters per frame, and the ranges that took most bytes. The +/// counters run from line to line, so they are divided by the frames +/// presented since the last line, not by `frames` (the frames of the last +/// second or more: a 4 s frame after an unlogged 4 s frame showed two +/// frames' counts as one's). pub(crate) fn log(frames: f64) { + let counted = COUNT[C::Frames as usize].swap(0, Relaxed); + let frames = if counted > 0 { counted as f64 } else { frames }; static FAULTS: AtomicU64 = AtomicU64::new(0); let faults = page_faults(); let faults = faults - FAULTS.swap(faults, Relaxed).min(faults); @@ -127,19 +1094,207 @@ pub(crate) fn log(frames: f64) { mb(c[C::TexHashed as usize]), mb(c[C::TexChanged as usize]), ); - let (registered_count, registered_bytes, loose_count, loose_bytes) = - crate::shadow::cache_stats(); - let (placed_count, placed_bytes) = crate::resource::placed_texture_cache_stats(); - let kept_slots = crate::descriptor::host::kept_slots(); tracing::info!( - "retained GPU mirrors: {registered_count} registered shadows ({:.1} MiB); {loose_count} loose shadows ({:.1} MiB); {placed_count} placed textures ({:.1} MiB estimated); {kept_slots} descriptor slots holding resources", - registered_bytes as f64 / (1 << 20) as f64, - loose_bytes as f64 / (1 << 20) as f64, - placed_bytes as f64 / (1 << 20) as f64, + "recording per frame ({frames:.0} frames): {:.0} list calls {:.1} ms (all recording \ + threads); {:.1} ms waiting for pipelines; dynamic slots: {:.0} tables asked, {:.0} \ + refused, {:.1} ms searching; notes {:.1} ms; shader-written ranges: {:.0} steps in \ + {:.1} submissions, snapshots {:.1} ms, {:.1} MB compared back; sparse reads {:.1} ms; \ + guards {:.1} ms; {:.1} MB copied whole (memory not watched); {:.1} frame waits \ + sleeping {:.1} ms (all threads); ranges of shaders that cannot store to buffers: \ + {:.0} steps {:.1} MB left out", + c[C::RecordCalls as usize], + c[C::RecordNs as usize] / 1e6, + ms(c[C::PipelineWaitUs as usize]), + c[C::DynamicAsked as usize], + c[C::DynamicRefused as usize], + c[C::DynamicNs as usize] / 1e6, + c[C::NoteNs as usize] / 1e6, + c[C::GpuWrites as usize], + c[C::BackSubmissions as usize], + ms(c[C::SnapshotUs as usize]), + mb(c[C::BackCompared as usize]), + ms(c[C::SparseUs as usize]), + ms(c[C::GuardUs as usize]), + mb(c[C::WholeBytes as usize]), + c[C::PaceWaits as usize], + ms(c[C::PaceUs as usize]), + c[C::GpuWritesLeftOut as usize], + mb(c[C::GpuWritesLeftOutBytes as usize]), + ); + // Where the wall clock of a frame goes: the phases of a frame, the + // processor time of the whole process, and what each submitting and + // recording thread did. + static CPU: Mutex<(u64, u64)> = Mutex::new((0, 0)); + let (user, kernel) = process_times(); + let (user, kernel) = { + let mut last = CPU.lock().unwrap_or_else(|e| e.into_inner()); + let spent = (user.saturating_sub(last.0), kernel.saturating_sub(last.1)); + *last = (user, kernel); + (spent.0 as f64 / 1e3 / frames, spent.1 as f64 / 1e3 / frames) + }; + tracing::info!( + "frame account per frame: after a present {:.1} ms until the first list call and {:.1} ms \ + until the first submission; {:.1} ms from the last submission to the present call; \ + lists reset in {:.1} ms; the process ran {user:.0} ms user + {kernel:.0} ms kernel on \ + all threads; what shaders wrote: {:.1} ms finding {:.0} pieces that differ, {:.1} ms \ + putting them back; texture uploads: {:.0} recorded, {:.0} left out; {:.1} held \ + submissions run at the present with their waits not met; waits for memory values: \ + {:.0} looks {:.1} ms; {:.0} host lists made {:.1} ms; {:.0} parts of held submissions \ + ran alone that the next part could have run with", + ms(c[C::UntilRecordUs as usize]), + ms(c[C::UntilSubmitUs as usize]), + ms(c[C::TailUs as usize]), + c[C::ResetNs as usize] / 1e6, + ms(c[C::BackScanUs as usize]), + c[C::BackDiffer as usize], + ms(c[C::BackSyncUs as usize]), + c[C::TexUploads as usize], + c[C::TexSkipped as usize], + c[C::Forced as usize], + c[C::WaitChecks as usize], + c[C::WaitCheckNs as usize] / 1e6, + c[C::HostLists as usize], + c[C::HostListNs as usize] / 1e6, + c[C::PartsTogether as usize], + ); + // What is copied whole, largest first: memory nobody tells us about. + let whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut whole: Vec<_> = whole.into_iter().flatten().collect(); + whole.sort_unstable_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); + tracing::info!( + " copied whole (memory not watched): {:.1} ms per frame in {} ranges; the largest follow", + ms(c[C::WholeUs as usize]), + whole.len() ); + for ((src, len), (n, us)) in whole.into_iter().take(6) { + tracing::info!( + " copied whole from {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame", + n as f64 / frames, + (len as u64 * n) as f64 / 1e6 / frames, + us as f64 / 1e3 / frames + ); + } + // The waiting for the card: many short waits or a few long ones, how + // much of it is for submissions the title gets nothing back from, and + // the longest one. + let longest = std::mem::take(&mut *LONGEST.lock().unwrap_or_else(|e| e.into_inner())); + tracing::info!( + " waiting for the card per frame: {:.1} submissions under 2 ms ({:.1} ms), {:.1} of 2-8 ms \ + ({:.1} ms), {:.1} of 8-32 ms ({:.1} ms), {:.1} longer ({:.1} ms); {:.1} submissions hand \ + nothing back to the title ({:.1} ms of the waiting); the longest since the last line: \ + {:.1} ms, {}", + c[C::CardUnder2 as usize], + ms(c[C::CardUnder2Us as usize]), + c[C::Card2To8 as usize], + ms(c[C::Card2To8Us as usize]), + c[C::Card8To32 as usize], + ms(c[C::Card8To32Us as usize]), + c[C::CardOver32 as usize], + ms(c[C::CardOver32Us as usize]), + c[C::NothingBack as usize], + ms(c[C::NothingBackUs as usize]), + longest.0 as f64 / 1e3, + longest.1 + ); + let by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut by: Vec<_> = by.into_iter().flatten().collect(); + by.sort_unstable_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); + for (what, (n, us)) in by.into_iter().take(12) { + tracing::info!( + " the card's time by what ran: {:.1} ms a frame in {:.1} submissions a frame: {}", + us as f64 / 1e3 / frames, + n as f64 / frames, + what.chars().take(700).collect::() + ); + } + let by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut by: Vec<_> = by.into_iter().flatten().collect(); + by.sort_unstable_by_key(|&(_, (_, us, _))| std::cmp::Reverse(us)); + // All of them together, and by their first word: the forty lines below + // are the heaviest only (100 of 226 ms waited in run 102), and what the + // commands do not account for is the layer's own lists (the card + // copies' passes, preludes) and the waits themselves. + if !by.is_empty() { + let mut kinds: Vec<(String, u64, u64)> = Vec::new(); + for (what, (n, us, _)) in &by { + let word = what.split(' ').next().unwrap_or("").to_owned(); + match kinds.iter_mut().find(|k| k.0 == word) { + Some(k) => (k.1, k.2) = (k.1 + n, k.2 + us), + None => kinds.push((word, *n, *us)), + } + } + kinds.sort_unstable_by_key(|k| std::cmp::Reverse(k.2)); + let all: u64 = kinds.iter().map(|k| k.2).sum(); + let text: Vec = + kinds.iter().map(|(word, n, us)| format!("{word} {:.1} ms in {:.0}", *us as f64 / 1e3 / frames, *n as f64 / frames)).collect(); + tracing::info!( + " the card's time by command (timing run), all {} kinds together: {:.1} ms a frame; by first word: {}", + by.len(), + all as f64 / 1e3 / frames, + text.join(", ") + ); + } + for (what, (n, us, longest)) in by.into_iter().take(40) { + tracing::info!( + " the card's time by command (timing run): {:.2} ms a frame in {:.1} commands a frame, the longest {:.2} ms: {what}", + us as f64 / 1e3 / frames, + n as f64 / frames, + longest as f64 / 1e3 + ); + } + tracing::info!( + " waits for every earlier shader write, per frame: {:.0} for the title's barrier groups, {:.0} \ + for its barriers on buffers; {:.0} indirect commands bounded (a dispatch of ours between two \ + such waits each); barrier experiment {}", + c[C::WaitsForGroups as usize], + c[C::WaitsForBuffers as usize], + c[C::IndirectBounded as usize], + barrier_test() + ); + // What is compared after submissions, largest first, and how much of + // it shaders had written. + let compared = COMPARED.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut compared: Vec<_> = compared.into_iter().flatten().collect(); + compared.sort_unstable_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); + tracing::info!(" compared after submissions: {} ranges; the largest follow", compared.len()); + for ((src, len), (n, written)) in compared.into_iter().take(8) { + tracing::info!( + " compared {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.3} MB/frame of it written back", + n as f64 / frames, + (len as u64 * n) as f64 / 1e6 / frames, + written as f64 / 1e6 / frames + ); + } + let mut submitters = std::mem::take(&mut *SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner())); + submitters.sort_unstable_by_key(|s| std::cmp::Reverse(s.1.submissions)); + for (id, s) in submitters.into_iter().take(4) { + let per = |v: u64| v as f64 / 1e3 / frames; + tracing::info!( + " thread {id} submitted {:.1}x/frame: between its submissions {:.1} ms (running \ + {:.1} ms user + {:.1} ms kernel; {:.1} ms in list calls), in them running {:.1} ms \ + user + {:.1} ms kernel, {:.1} ms waiting for the submission lock", + s.submissions as f64 / frames, + per(s.between), + per(s.between_user), + per(s.between_kernel), + s.between_ours as f64 / 1e6 / frames, + per(s.inside_user), + per(s.inside_kernel), + per(s.lock), + ); + } + let mut recorders = std::mem::take(&mut *RECORDERS.lock().unwrap_or_else(|e| e.into_inner())); + recorders.sort_unstable_by_key(|r| std::cmp::Reverse(r.1)); + let busiest: Vec = recorders + .iter() + .take(6) + .map(|r| format!("thread {} {:.0} ms in {:.0} calls", r.0, r.1 as f64 / 1e6 / frames, r.2 as f64 / frames)) + .collect(); + tracing::info!(" list calls by thread: {} threads; {}", recorders.len(), busiest.join(", ")); + log_memory(); let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut ranges: Vec<_> = ranges.into_iter().flatten().collect(); - ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes)); + ranges.sort_unstable_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes)); for ((src, len), (n, bytes, us, _)) in ranges.into_iter().take(10) { use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; // SAFETY: plain data filled in by the query. diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index e3c4176..8485014 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -34,7 +34,7 @@ pub(crate) struct HeapDesc { nodes: u32, } -/// Newer titles (Grand Theft Auto VI) pass the description followed by +/// Newer titles (the title) pass the description followed by /// memory of their own for the descriptors: an address and its size in /// bytes, or a null address to have the heap allocate (inferred from the /// title's call sites; older titles pass the plain description). @@ -59,11 +59,6 @@ pub(crate) struct Heap { host: std::sync::OnceLock>, #[cfg(windows)] pending: std::sync::Mutex>, - /// The write-watch asking (see [`crate::watch::writes`]) up to which - /// the host heap has caught up with what the title wrote into its - /// memory itself (see [`resync_title_writes`]). - #[cfg(windows)] - synced: std::sync::atomic::AtomicU64, } pub(crate) fn heap<'a>(this: This) -> &'a Heap { @@ -73,13 +68,12 @@ pub(crate) fn heap<'a>(this: This) -> &'a Heap { impl Heap { /// Whether this is a sampler heap. - #[cfg(windows)] pub(crate) fn samplers(&self) -> bool { self.desc.kind == SAMPLERS } /// The host heap, made on first use from what the title wrote so far. - /// Made late because a host view heap the size of Grand Theft Auto VI's + /// Made late because a host view heap the size of the title's /// costs over 100 MB of commit, which its boot needs for its page pool. #[cfg(windows)] pub(crate) fn host(&self) -> Option<&host::HostHeap> { @@ -105,8 +99,14 @@ impl Heap { .as_ref() } - /// The descriptor index of `handle` in this heap, if it lies in it. + /// The handle of descriptor `index` of this heap. #[cfg(windows)] + pub(crate) fn handle(&self, index: u32) -> Option { + let step = u64::from(increment(self.desc.kind)?); + (index < self.desc.count).then(|| self.start + u64::from(index) * step) + } + + /// The descriptor index of `handle` in this heap, if it lies in it. pub(crate) fn index(&self, handle: u64) -> Option { let step = u64::from(increment(self.desc.kind)?); let at = handle.checked_sub(self.start)?; @@ -155,49 +155,6 @@ fn mirror(handle: u64) { } } -/// Brings the host heaps up to date with descriptors the title wrote into -/// heap memory itself (copies of whole slots, which no create or copy call -/// reports), before a submission runs: slots read directly by index (not -/// through a table) are made only from what was mirrored, so a slot the -/// title turned from a texture into a constant buffer kept the texture, -/// whose upper half the shader read as a buffer at address 0: a GPU page -/// fault and a lost device in the world. Only the 64 KiB blocks written -/// since the last call are looked at; heaps in memory the kernel does not -/// watch (ours, not the title's) are left as they are. -#[cfg(windows)] -pub(crate) fn resync_title_writes() { - use std::sync::atomic::Ordering::Relaxed; - // Held throughout: registered heaps stay alive while it is. - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); - for &(start, end, at) in heaps.iter() { - // SAFETY: registered heaps are live (removed when dropped). - let heap = unsafe { &*(at as *const Heap) }; - let (Some(Some(host)), Some(step)) = (heap.host.get(), increment(heap.desc.kind)) else { - continue; // no host heap yet: its first use mirrors everything - }; - let page = crate::watch::PAGE as u64; - let (first, last) = (start / page * page, end.div_ceil(page) * page); - let Some((now, written)) = crate::watch::writes(first as usize, last as usize, true) else { - continue; - }; - let before = heap.synced.swap(now, Relaxed); - let step = u64::from(step); - for (p, asked) in written { - if asked <= before { - continue; - } - let from = (p as u64 * page).max(start); - let to = ((p as u64 + 1) * page).min(end); - for i in (from - start) / step..(to - start).div_ceil(step) { - let i = i as u32; - if i < heap.desc.count { - host.mirror(i, start + u64::from(i) * step, false); - } - } - } - } -} - /// Gives back dynamic slots of the host heap behind the title heap at /// `heap`, if that heap still exists. #[cfg(windows)] @@ -281,7 +238,8 @@ impl RtvRecord { 0, ] }; - words[0] = crate::resource::pc_format(words[0]); + // A target or depth view: of a target, in its stand-in format. + words[0] = crate::resource::target_format(crate::resource::pc_format(words[0])); // SAFETY: both host view descriptions are 24 bytes in this layout. Some(unsafe { (&raw const words).cast::().read_unaligned() }) } @@ -368,9 +326,21 @@ impl View { /// generation, so descriptors (and host slots made from them) naming the /// old one go stale instead of naming whatever is made at the same address /// next. -/// shortcut: views without a resource object (constant buffers, memory -/// views, samplers) are kept for the run; they are bounded by the title's -/// memory and sampler states. +/// +/// Views without a resource object have nothing that releases them, and a +/// title copies descriptors as bytes, so nothing says when the last +/// descriptor naming an entry is gone: such entries were kept for the run. +/// The title writes some 14,000 constant buffer views a frame, +/// each at the address its constants have that frame: 2,450,139 entries +/// after four minutes of play, 1,047 MB with the index, and 11,000 more +/// every second (run 65). So the two kinds that carry an address are not +/// entries any more: their records name them whole ([`constant_words`], +/// [`placed_words`]), and the table holds only what is bounded: views of +/// resource objects (freed with the resource), samplers (as many as there +/// are sampler states), and the shapes of placed views (their descriptions +/// without the address: as many as the title has kinds of textures and +/// buffers, however often it moves them). +/// `VICTORY_VIEW_INLINE=0`: every view is an entry, as before. struct Views { /// Each entry's view and generation. list: Vec<(View, u32)>, @@ -378,6 +348,9 @@ struct Views { /// Entries naming each resource. by_resource: std::collections::BTreeMap>, free: Vec, + /// The shapes of views of placed memory, and where each is. + shapes: Vec, + shape_index: std::collections::BTreeMap, } static VIEWS: std::sync::Mutex = std::sync::Mutex::new(Views { @@ -385,9 +358,220 @@ static VIEWS: std::sync::Mutex = std::sync::Mutex::new(Views { index: std::collections::BTreeMap::new(), by_resource: std::collections::BTreeMap::new(), free: Vec::new(), + shapes: Vec::new(), + shape_index: std::collections::BTreeMap::new(), }); const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE"); +/// A record is the tag and two words, `i` and `generation` (the host keeps +/// them as one 64-bit key per slot). The top two bits of `generation` say +/// what the other 62 bits are: 0, entry `i` of the table at that +/// generation; [`CONSTANT`], a constant buffer view, whole; [`PLACED`], a +/// view of placed memory: its address and the number of its shape. +const KIND_SHIFT: u32 = 30; +/// Table generations stay below the kind bits (and above 0). +const GENERATIONS: u32 = (1 << KIND_SHIFT) - 1; +const CONSTANT: u32 = 1; +const PLACED: u32 = 2; +/// Bits of a constant buffer view's address in its record: any address a +/// program can have. The 15 bits above them are its size. +const CONSTANT_ADDRESS_BITS: u32 = 47; +/// Bits of a placed view's address in its record: placed memory is title +/// memory, which lies below 1 TiB. The 22 bits above them number its shape. +const PLACED_ADDRESS_BITS: u32 = 40; +const SHAPES: usize = 1 << (62 - PLACED_ADDRESS_BITS); + +/// A view of placed memory without its address: whether it is unordered +/// access, the resource description, and the view's words but the two that +/// hold the address (10 and 11). +type Shape = (bool, [u32; 14], [u32; 14]); + +/// Whether constant buffer views and views of placed memory are named whole +/// in their records ([`Views`]). On by default; `VICTORY_VIEW_INLINE=0` +/// makes every view a table entry, as before. +fn inline() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_INLINE").is_none_or(|v| v != "0")) +} + +/// Views named whole in their records since the start: constant buffer +/// views, views of placed memory (for the memory line). +static NAMED_WHOLE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The two record words of the 62 bits `payload` of kind `kind`. +fn kind_words(kind: u32, payload: u64) -> [u32; 2] { + [payload as u32, kind << KIND_SHIFT | (payload >> 32) as u32] +} + +/// The 62 bits two record words carry beside their kind. +fn payload(i: u32, generation: u32) -> u64 { + u64::from(generation & GENERATIONS) << 32 | u64::from(i) +} + +/// The record words that name the constant buffer view of `size` bytes at +/// `address` whole; `None` if they cannot: an address past 47 bits, or a +/// size of 16 KiB or more that is no multiple of 256 or reaches 4 MiB (the +/// size has 15 bits: bytes below 16 KiB, else units of 256 bytes). Such a +/// view is a table entry. +fn constant_words(address: u64, size: u32) -> Option<[u32; 2]> { + if address >> CONSTANT_ADDRESS_BITS != 0 { + return None; + } + let code = if size < 1 << 14 { + u64::from(size) + } else if size.is_multiple_of(256) && size >> 8 < 1 << 14 { + 1 << 14 | u64::from(size >> 8) + } else { + return None; + }; + Some(kind_words(CONSTANT, code << CONSTANT_ADDRESS_BITS | address)) +} + +/// The constant buffer view [`constant_words`] named. +fn constant_of(i: u32, generation: u32) -> View { + let payload = payload(i, generation); + let code = (payload >> CONSTANT_ADDRESS_BITS) as u32; + let size = if code >> 14 == 0 { code } else { (code & 0x3fff) << 8 }; + View::Constant(payload & ((1 << CONSTANT_ADDRESS_BITS) - 1), size) +} + +/// A placed view's shape and its address. +fn shape_of(unordered: bool, resource: &[u32; 14], desc: &[u32; 16]) -> (Shape, u64) { + let mut rest = [0u32; 14]; + rest[..10].copy_from_slice(&desc[..10]); + rest[10..].copy_from_slice(&desc[12..]); + ( + (unordered, *resource, rest), + u64::from(desc[10]) | u64::from(desc[11]) << 32, + ) +} + +/// The record words that name the view of placed memory at `address` with +/// shape number `shape`. +fn placed_words(shape: u32, address: u64) -> [u32; 2] { + kind_words(PLACED, u64::from(shape) << PLACED_ADDRESS_BITS | address) +} + +impl Views { + /// The number of `shape`, a new one if it is not there yet; `None` when + /// the shapes are full (the view is then a table entry). + fn shape(&mut self, shape: Shape) -> Option { + if let Some(&at) = self.shape_index.get(&shape) { + return Some(at); + } + if self.shapes.len() >= SHAPES { + return None; + } + let at = self.shapes.len() as u32; + self.shapes.push(shape); + self.shape_index.insert(shape, at); + Some(at) + } + + /// The view of placed memory [`placed_words`] named. + fn placed_of(&self, i: u32, generation: u32) -> Option { + let payload = payload(i, generation); + let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1); + let &(unordered, resource, rest) = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?; + let mut desc = [0u32; 16]; + desc[..10].copy_from_slice(&rest[..10]); + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + desc[12..].copy_from_slice(&rest[10..]); + Some(View::Placed(unordered, resource, desc)) + } + + /// The record words of `view` as a table entry: its entry (a new or a + /// freed one if the view is not there yet) and that entry's generation. + fn entry(&mut self, view: View) -> [u32; 2] { + let i = match self.index.get(&view) { + Some(&i) => i, + None => { + let i = match self.free.pop() { + Some(i) => { + self.list[i as usize].0 = view.clone(); + i + } + None => { + self.list.push((view.clone(), 1)); + self.list.len() as u32 - 1 + } + }; + for r in view.resources().into_iter().filter(|&r| r != 0) { + self.by_resource.entry(r).or_default().push(i); + } + self.index.insert(view, i); + i + } + }; + [i, self.list[i as usize].1] + } +} + +/// The two words that name `view` in a record: the view itself where its +/// kind allows ([`Views`]), else its table entry. +fn words_for(view: View) -> [u32; 2] { + use std::sync::atomic::Ordering::Relaxed; + if inline() { + match &view { + View::Constant(address, size) => { + if let Some(words) = constant_words(*address, *size) { + NAMED_WHOLE[0].fetch_add(1, Relaxed); + return words; + } + } + View::Placed(unordered, resource, desc) => { + let (shape, address) = shape_of(*unordered, resource, desc); + if address >> PLACED_ADDRESS_BITS == 0 { + let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(shape) = views.shape(shape) { + NAMED_WHOLE[1].fetch_add(1, Relaxed); + return placed_words(shape, address); + } + } + } + _ => {} + } + } + VIEWS.lock().unwrap_or_else(|e| e.into_inner()).entry(view) +} + +/// For the memory line: the distinct views kept ([`Views`]), those of them +/// free for reuse, and the bytes the table and its index hold for them (an +/// estimate: an entry of the table, and one of the index with its share of +/// a tree node; the shapes likewise); then the entries that are constant +/// buffer views and views of placed memory (those that did not fit a +/// record, or all of them with `VICTORY_VIEW_INLINE=0`), the shapes of +/// placed views kept, and the views named whole in their records since the +/// start: constant buffer views, views of placed memory. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn views_kept() -> [u64; 8] { + use std::sync::atomic::Ordering::Relaxed; + let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let each = size_of::<(View, u32)>() as u64; + let shape = size_of::() as u64; + let (mut constants, mut placed) = (0, 0); + for (view, _) in &views.list { + match view { + View::Constant(..) => constants += 1, + View::Placed(..) => placed += 1, + _ => {} + } + } + [ + views.list.len() as u64, + views.free.len() as u64, + views.list.capacity() as u64 * each + + views.index.len() as u64 * each * 3 / 2 + + views.shapes.capacity() as u64 * shape + + views.shape_index.len() as u64 * shape * 3 / 2, + constants, + placed, + views.shapes.len() as u64, + NAMED_WHOLE[0].load(Relaxed), + NAMED_WHOLE[1].load(Relaxed), + ] +} + impl View { /// The resource objects the view names. fn resources(&self) -> [usize; 2] { @@ -397,44 +581,122 @@ impl View { _ => [0, 0], } } + + /// The texture object the view is of, if that texture has no host copy + /// yet (`crate::resource::host_waits`): a slot written with such a + /// view is left null until the texture is first used. + #[cfg(windows)] + fn waiting_texture(&self) -> Option { + match *self { + View::Shader(r, _) | View::Unordered(r, _, _) + if crate::resource::host_waits(r as This) => + { + Some(r) + } + _ => None, + } + } } -fn record(handle: u64, view: View) { - if handle == 0 { - return; +/// Title slots (their handles) written with a view of a texture object +/// that had no host copy then, by texture. A title texture gets its host +/// copy on first use (`resource.rs` `Hosted`), and the title +/// writes each texture's views into its view heap when it creates the +/// texture: making those host slots would make every host copy at once. +/// They are made when the texture is: translated shaders index the heap +/// directly, so a slot is not always made again by the draw that reads it. +#[cfg(windows)] +static WAITING: std::sync::Mutex>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// Textures given their host copy since [`make_waiting`] last ran. +#[cfg(windows)] +static MADE_LATE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Title texture `resource` was given its host copy (called under that +/// texture's own lock: nothing else is locked here). +#[cfg(windows)] +pub(crate) fn texture_made(resource: usize) { + MADE_LATE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(resource); +} + +/// The slot at `handle` was written with a view of texture `resource`, +/// which has no host copy: it waits for one. +#[cfg(windows)] +fn wait_for(resource: usize, handle: u64) { + /// A texture with more slots waiting than this is in use for all we + /// know (its views are being copied about): its host copy is made. + const MOST: usize = 64; + let many = { + let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()); + let slots = waiting.entry(resource).or_default(); + if !slots.contains(&handle) { + slots.push(handle); + } + slots.len() > MOST + }; + if many { + // Makes it, and notes it made. + let _ = crate::resource::host_copy(resource as This); + } else if !crate::resource::host_waits(resource as This) { + // Made by another thread since the slot was looked at: that making + // may have been taken by `make_waiting` before this slot was noted. + texture_made(resource); } - let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); - let i = match views.index.get(&view) { - Some(&i) => i, - None => { - let i = match views.free.pop() { - Some(i) => { - views.list[i as usize].0 = view.clone(); - i - } - None => { - views.list.push((view.clone(), 1)); - views.list.len() as u32 - 1 - } +} + +/// Makes the host slots that waited for a texture's host copy, for the +/// textures made since the last call. Called before a submission runs, by +/// the thread that submits: a slot is read when a list runs. +#[cfg(windows)] +pub(crate) fn make_waiting() { + let made = std::mem::take(&mut *MADE_LATE.lock().unwrap_or_else(|e| e.into_inner())); + for resource in made { + let handles = WAITING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&resource); + for handle in handles.into_iter().flatten() { + // Only if the slot still holds a view of that texture: the + // title may have written it since (and a view of another + // texture without a host copy must go on waiting). + // (Looked up first: the handle is read only while its heap is + // there.) + let Some((heap, index)) = shader_slot(handle) else { + continue; + }; + let same = match view(handle) { + Some(View::Shader(r, _) | View::Unordered(r, _, _)) => r == resource, + _ => false, }; - for r in view.resources().into_iter().filter(|&r| r != 0) { - views.by_resource.entry(r).or_default().push(i); + if same && let Some(Some(host)) = heap.host.get() { + host.mirror(index, handle, true); } - views.index.insert(view, i); - i } - }; - let generation = views.list[i as usize].1; + } +} + +fn record(handle: u64, view: View) { + if handle == 0 { + return; + } + let [i, generation] = words_for(view); // SAFETY: the handle is a descriptor slot, at least 16 bytes. unsafe { (handle as *mut [u32; 3]).write_unaligned([VIEW_TAG, i, generation]) }; - drop(views); #[cfg(windows)] mirror(handle); } /// The title released `resource`: the views naming it go stale. -#[cfg(any(windows, test))] pub(crate) fn forget(resource: usize) { + #[cfg(windows)] + WAITING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&resource); let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); let Some(entries) = views.by_resource.remove(&resource) else { return; @@ -447,32 +709,40 @@ pub(crate) fn forget(resource: usize) { continue; } views.index.remove(&view); - views.list[i as usize].1 = generation.wrapping_add(1).max(1); + // (Below the bits that say a record is no table entry.) + views.list[i as usize].1 = ((generation + 1) & GENERATIONS).max(1); // The view's other resource (a counter) keeps a stale entry, which // `forget` of that resource skips. views.free.push(i); } } -/// The view of entry `i` if `generation` is still its own. -#[cfg(windows)] +/// The view the record words `i` and `generation` name: the one they hold +/// whole, or the view of entry `i` if `generation` is still its own. fn view_at(i: u32, generation: u32) -> Option { - let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); - let (view, current) = views.list.get(i as usize)?; - (*current == generation).then(|| view.clone()) + match generation >> KIND_SHIFT { + 0 => { + let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let (view, current) = views.list.get(i as usize)?; + (*current == generation).then(|| view.clone()) + } + CONSTANT => Some(constant_of(i, generation)), + PLACED => VIEWS.lock().unwrap_or_else(|e| e.into_inner()).placed_of(i, generation), + _ => None, + } } /// The view recorded at `handle`, if one is (and its resource is alive). -#[cfg(any(windows, test))] pub(crate) fn view(handle: u64) -> Option { if handle == 0 { return None; } // SAFETY: the handle is a descriptor slot the title passes back. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; - let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); - let (view, current) = views.list.get(i as usize)?; - (tag == VIEW_TAG && *current == generation).then(|| view.clone()) + if tag != VIEW_TAG { + return None; + } + view_at(i, generation) } /// A description of `N` words, if the title passes one. @@ -616,18 +886,15 @@ pub(crate) extern "system" fn copy( } /// The view recorded at `handle`, if one is. -#[cfg(windows)] pub(crate) fn rtv_record(handle: u64) -> Option { tagged_record(handle, RTV_TAG) } /// The depth view recorded at `handle`, if one is. -#[cfg(windows)] pub(crate) fn dsv_record(handle: u64) -> Option { tagged_record(handle, DSV_TAG) } -#[cfg(windows)] fn tagged_record(handle: u64, tag: u32) -> Option { if handle == 0 { return None; @@ -679,8 +946,6 @@ pub(crate) extern "system" fn create_heap( host: std::sync::OnceLock::new(), #[cfg(windows)] pending: Default::default(), - #[cfg(windows)] - synced: std::sync::atomic::AtomicU64::new(0), }); #[cfg(windows)] if visible { @@ -723,9 +988,6 @@ static FUNCTIONS: Table<24> = { Table(f) }; -#[cfg(all(test, windows))] -pub(crate) use tests::test_view_heap; - #[cfg(test)] mod tests { use super::*; @@ -741,28 +1003,6 @@ mod tests { create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out) } - #[cfg(windows)] - pub(crate) fn test_view_heap(count: u32) -> This { - let mut heap = std::ptr::null(); - assert_eq!( - create( - HeapDesc { - kind: VIEWS_KIND, - count, - flags: SHADER_VISIBLE, - nodes: 0, - }, - Placement { - address: 0, - size: 0, - }, - &mut heap, - ), - S_OK - ); - heap - } - #[test] fn heaps_hold_count_descriptors_from_their_start() { let null = std::ptr::null(); @@ -823,6 +1063,81 @@ mod tests { heap[0] = 0; } + /// Constant buffer views are named whole in their records: any address + /// a program can have, any size below 16 KiB, multiples of 256 bytes + /// up to 4 MiB; what does not fit says so. + #[test] + fn constant_views_fit_their_records() { + let top = (1u64 << CONSTANT_ADDRESS_BITS) - 1; + for address in [0u64, 0x100, 0x2602_0000, 0xd_6b60_0000, 0x7ffd_a34f_0000, top] { + for size in [0u32, 1, 255, 256, 4000, (1 << 14) - 1, 1 << 14, 65536, (1 << 22) - 256] { + let [i, generation] = constant_words(address, size).expect("fits"); + assert_eq!(generation >> KIND_SHIFT, CONSTANT); + assert_eq!(view_at(i, generation), Some(View::Constant(address, size)), "{address:#x} {size}"); + } + } + assert_eq!(constant_words(top + 1, 256), None, "an address past 47 bits"); + assert_eq!(constant_words(0x1000, (1 << 14) + 1), None, "16 KiB or more, no multiple of 256"); + assert_eq!(constant_words(0x1000, 1 << 22), None, "4 MiB"); + // Different views never share their words. + assert_ne!(constant_words(0x1000, 256), constant_words(0x1000, 512)); + assert_ne!(constant_words(0x1000, 256), constant_words(0x1100, 256)); + assert_ne!(constant_words(0x1000, 1 << 14), constant_words(0x1000, 64)); + } + + /// The leak of run 65: a title that writes constant buffer views and + /// views of placed memory at ever new addresses adds nothing to the + /// table; one shape stands for all the placed views alike. + #[test] + fn views_at_new_addresses_add_no_entries() { + if !inline() { + return; + } + let null = std::ptr::null(); + let slots = [0u64; 4]; + let at = slots.as_ptr() as u64; + // A resource description and a view no other test uses. + let resource: [u32; 14] = std::array::from_fn(|k| 0x5ee0_0000 + k as u32); + let mut desc: [u32; 16] = std::array::from_fn(|k| 0x7a70_0000 + k as u32); + let mine = |v: &View| match v { + View::Constant(address, _) => (0x6_0000_0000..0x6_1000_0000).contains(address), + View::Placed(_, r, _) => *r == resource, + _ => false, + }; + let entries = || VIEWS.lock().unwrap().list.iter().filter(|(v, _)| mine(v)).count(); + let shapes = || VIEWS.lock().unwrap().shapes.iter().filter(|s| s.1 == resource).count(); + for n in 0..20_000u64 { + let address = 0x6_0000_0000 + n * 0x100; + create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at); + assert_eq!(view(at), Some(View::Constant(address, 512))); + let placed = 0xd_4940_0000 + n * 0x1_0000; + (desc[10], desc[11]) = (placed as u32, (placed >> 32) as u32); + create_placed_srv(null, &resource, &desc, at); + assert_eq!(view(at), Some(View::Placed(false, resource, desc))); + } + assert_eq!(entries(), 0, "no table entries"); + assert_eq!(shapes(), 1, "one shape for 20,000 placed views"); + // The same shape, unordered: another shape. + create_placed_uav(null, &resource, &desc, at); + assert_eq!(view(at), Some(View::Placed(true, resource, desc))); + assert_eq!(shapes(), 2); + // Placed memory past 1 TiB (not title memory) is a table entry. + (desc[10], desc[11]) = (0, 0x100); + create_placed_srv(null, &resource, &desc, at); + assert_eq!(view(at), Some(View::Placed(false, resource, desc))); + assert_eq!(entries(), 1); + // A record's words are the same for the same view (the host knows + // a slot's view by them), and differ with the address. + // SAFETY: both handles are slots of 32 bytes above. + let words = |handle: u64| unsafe { *(handle as *const [u32; 3]) }; + let other = [0u64; 4]; + create_cbv(null, &[0x40, 6, 512, 0], at); + create_cbv(null, &[0x40, 6, 512, 0], other.as_ptr() as u64); + assert_eq!(words(at), words(other.as_ptr() as u64)); + create_cbv(null, &[0x140, 6, 512, 0], other.as_ptr() as u64); + assert_ne!(words(at), words(other.as_ptr() as u64)); + } + /// A released resource's views go stale; the same view of a new /// resource at the same address is a new record. #[test] @@ -842,7 +1157,7 @@ mod tests { assert_ne!(old, new, "a new generation"); } - /// Grand Theft Auto VI places its shader-visible heap in its own memory + /// The title places its shader-visible heap in its own memory /// and checks that the heap starts there. #[test] fn placed_heaps_start_at_the_title_memory() { diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 33c16f5..7b18b45 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -13,27 +13,16 @@ use windows::Win32::Graphics::Dxgi::Common::*; use super::{VIEW_TAG, View, view_at}; use crate::host::host; -/// Number of shader-visible descriptor slots retaining a host resource. -#[cfg(feature = "diagnostics")] -static KEPT_SLOTS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -#[cfg(feature = "diagnostics")] -pub(crate) fn kept_slots() -> usize { - KEPT_SLOTS.load(std::sync::atomic::Ordering::Relaxed) -} - pub(crate) struct HostHeap { pub(crate) heap: ID3D12DescriptorHeap, cpu: usize, step: u32, /// Slots mirroring the title's; view heaps have `dynamic` more. count: u32, - /// Dynamic slots past `count` (none in sampler heaps): [`DYNAMIC`] - /// where the host takes them, else [`MIN_DYNAMIC`]. + /// Dynamic slots past `count`: [`DYNAMIC`] in view heaps, none in + /// sampler heaps. (Upstream falls back to 2^16 on a capped host heap; + /// ours keeps 2^18 there: 2^16 and 2^17 both ran out in this title.) dynamic: u32, - /// With shader breadcrumbs: the slot after the dynamic ones holds the - /// breadcrumb buffer's UAV (see [`crate::breadcrumb`]). - crumb: bool, sampler: bool, /// The record (view index and generation) each slot was last made from. made: Mutex>, @@ -45,10 +34,545 @@ pub(crate) struct HostHeap { /// Where the search for free dynamic slots starts, and which are taken /// (by lists not yet reset). next: Mutex<(u32, Vec)>, - /// View heaps: the console words of each slot's descriptor, 8 dwords - /// per slot, for shaders that read descriptors as numbers: the buffer, - /// its mapping and its host GPU address. - words: Option<(ID3D12Resource, usize, u64)>, + /// How many dynamic slots are free (changed under `next`'s lock): with + /// fewer than a table needs, the search is not made. Once the world + /// had taken them all, every later table of the frame searched every + /// slot before it was refused. + free: std::sync::atomic::AtomicU32, + /// The shortest table that found no run of free slots since slots were + /// last given back (changed under `next`'s lock; `u32::MAX`: none). + /// Until something is given back the free runs only shrink, so a table + /// of that length or longer is refused without the search. Enough + /// slots were free, but in pieces, and every such table walked the + /// whole ring before it was refused: 0.33 ms each with 131,072 slots, + /// 1.0 s of the recording threads in a frame that refused 3,143 (run + /// 45), under the lock all of them need. (A free run that lies across + /// the place the search starts from is seen by neither.) + too_long: std::sync::atomic::AtomicU32, + /// View heaps: the bytes per element of the buffer view at each title + /// slot, for shaders that pick a buffer by an index they compute + /// (`victory_shader::emit::SLOT_STRIDES`): an upload buffer of + /// `SLOT_STRIDES_COUNT` dwords, its GPU address and its mapping. + strides: Option<(ID3D12Resource, u64, usize)>, + /// Title slots holding buffer views. Such a view gets its host slot + /// (and its memory a host copy) only when something reads it: a draw + /// through a table, or [`HostHeap::buffer_slots`] for shaders that pick + /// buffers from the whole heap. + buffers: Mutex>, + /// Of those and of the slots that left the set: the ones written since + /// [`HostHeap::buffer_changes`] last took them. + changed: Mutex>, + /// Title slots holding a view of a texture the title may fill itself (a + /// placed texture, a texture object), with the frame from which they + /// are due: such a texture is uploaded when a draw reads it through a + /// table; one a shader picks by a computed index is brought up to date + /// from here ([`HostHeap::texture_slots_due`]). + textures: Mutex, + /// Per title slot, the frame (plus one; 0: never) in which a draw last + /// read it through a table, or made a table it lies in (with + /// [`TABLED_READ`] set if the draw read it). The draw that + /// reads such a slot brings its texture up to date itself and the slot + /// then leaves `textures`; a write of a slot that was a table's within + /// the last [`TABLED_FRAMES`] frames is due only [`TABLED_GRACE`] + /// frames later, by when its draw has read it. A title that builds a + /// table per draw writes thousands of texture views a frame into slots + /// only tables read (the title: some 2,500 a frame in its + /// opening cutscene, a few hundred textures over and over), and every + /// one of them stood in the queue of textures picked by index, ahead + /// of or behind the ones shaders do pick by index. + tabled: Vec, + /// The title memory each placed texture view of this heap describes, + /// by slot and by address ([`Spans`]): which slots a newer view of + /// other memory there makes stale, and which to look at again when the + /// runtime maps, unmaps or writes memory ([`remapped`]). + placed: Mutex, +} + +/// Title memory by the placed texture views that describe it: per span of +/// memory (its start, its end at full size) the title slots holding a +/// view of a texture that takes exactly that span. A console title need +/// not clear a descriptor when it streams a texture out, so a newer view +/// that cannot be there together with an older one is all that says the +/// older one is stale ([`Rule`] says when that is). Views of one span with +/// different descriptions (the formats of one family, say) are one +/// texture's. +/// +/// Spans may overlap: a texture's smallest levels lie at the start of its +/// memory, and a title that holds only those puts the next texture where +/// the larger ones would be (the title: three 512x256 textures +/// of 0x2c000 bytes each whose starts are 0x2000 and 0x4000 apart, all +/// three read by the same frame's draws, run 188). What is there of a +/// texture ends where the next one starts. +/// No host heap is needed, so it is tested without one. +#[derive(Default)] +pub(crate) struct Spans { + /// When a newer view makes an older one stale. + rule: Rule, + by_start: std::collections::BTreeMap)>, + by_slot: std::collections::HashMap, + /// The bytes a placed texture takes, by resource description: worked + /// out once for each (a title writes the views of a few thousand + /// descriptions, thousands of times a frame). + sizes: std::collections::HashMap<[u32; 14], Option>, +} + +/// When a view the title writes makes an older view of other memory stale. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Rule { + /// When it starts where the older one starts: at the same address + /// with another length, or within the older one's first [`HEAD`] + /// bytes (or the older within its own). No two textures share the + /// block of their smallest levels. A view that only reaches into the + /// address range of an older texture's larger levels says nothing. + #[default] + Start, + /// Whenever their spans at full size overlap (the rule until run + /// 188, where it made null the slots of textures packed as above: + /// each view written took its neighbours out of the queue and off the + /// card, for good). `VICTORY_STALE_TEXTURES=overlap`. + Overlap, + /// Never; a view that would be stale under [`Rule::Overlap`] is left + /// out of the spans instead. `VICTORY_STALE_TEXTURES=0`, as before. + Never, +} + +/// The first bytes of a placed texture that are its own under +/// [`Rule::Start`]: the 4 KiB block its smallest levels share. (Of 129 +/// pairs of overlapping neighbours in the listings of runs 188 and 189, +/// none starts closer than 0x2000 to the one before it.) +const HEAD: u64 = 4096; + +impl Spans { + /// The bytes of title memory a placed texture with the resource + /// description `desc` takes (`crate::resource::placed_bytes`). + fn bytes(&mut self, desc: &[u32; 14]) -> Option { + if let Some(&known) = self.sizes.get(desc) { + return known; + } + let bytes = crate::resource::placed_bytes(desc); + self.sizes.insert(*desc, bytes); + bytes + } + + /// The starts of the spans that overlap `[start, end)`, each taken to + /// end where the next one starts: the last span that starts before + /// `start`, if it reaches past it at full size, and every span that + /// starts inside. + fn overlapping(&self, start: u64, end: u64) -> Vec { + let before = self + .by_start + .range(..start) + .next_back() + .filter(|(_, span)| span.0 > start) + .map(|(at, _)| *at); + before.into_iter().chain(self.by_start.range(start..end).map(|(at, _)| *at)).collect() + } + + /// Slot `index` holds a view of a texture in `[start, end)`. `newer`: + /// the title wrote it now, so the slots whose views cannot be there + /// with it ([`Rule`]) are stale: they are returned, and forgotten. + /// Otherwise (a draw made the slot from what it held), and under + /// [`Rule::Never`], a view that clashes with other spans is left out. + fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec { + let same = |span: Option<&(u64, std::collections::BTreeSet)>| span.is_some_and(|s| s.0 == end); + if self.by_slot.get(&index) == Some(&start) && same(self.by_start.get(&start)) { + return Vec::new(); + } + self.forget(index); + if end <= start { + return Vec::new(); + } + let rule = self.rule; + // The spans the view cannot be there with. + let clashing: Vec = match rule { + Rule::Start => self + .by_start + .range(start.saturating_sub(HEAD - 1)..start.saturating_add(HEAD)) + .map(|(at, _)| *at) + .collect(), + Rule::Overlap | Rule::Never => self.overlapping(start, end), + }; + let mut stale = Vec::new(); + for at in clashing { + if at == start && same(self.by_start.get(&at)) { + continue; + } + if !newer || rule == Rule::Never { + return stale; + } + if let Some((old_end, slots)) = self.by_start.remove(&at) { + // The first of them are said with both spans, to tell a + // replacement from a neighbour in one launch's log. + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 48 { + tracing::info!( + slot = index, + start = format_args!("{start:#x}"), + end = format_args!("{end:#x}"), + stale_start = format_args!("{at:#x}"), + stale_end = format_args!("{old_end:#x}"), + stale_slots = slots.len(), + rule = ?rule, + "a placed texture view makes older views of other memory stale" + ); + } + for slot in slots { + self.by_slot.remove(&slot); + stale.push(slot); + } + } + } + self.by_start.entry(start).or_insert_with(|| (end, Default::default())).1.insert(index); + self.by_slot.insert(index, start); + stale + } + + /// Slot `index` holds no placed texture view any more. + fn forget(&mut self, index: u32) { + let Some(start) = self.by_slot.remove(&index) else { + return; + }; + if let Some(span) = self.by_start.get_mut(&start) { + span.1.remove(&index); + if span.1.is_empty() { + self.by_start.remove(&start); + } + } + } + + /// The slots whose texture's memory overlaps `[start, end)`. + fn slots_in(&self, start: u64, end: u64) -> Vec { + self.overlapping(start, end) + .iter() + .filter_map(|at| self.by_start.get(at)) + .flat_map(|span| span.1.iter().copied()) + .collect() + } +} + +/// Title memory the runtime mapped, unmapped or is about to write since a +/// texture pass last took the ranges ([`remapped`]). +static REMAPPED: Mutex> = Mutex::new(Vec::new()); + +/// The lowest start and the highest end of any span of [`Spans`] so far +/// (the start is `u64::MAX` until there is one): what the runtime does to +/// memory outside is none of the texture pass's business. +static SPANNED: [std::sync::atomic::AtomicU64; 2] = [ + std::sync::atomic::AtomicU64::new(u64::MAX), + std::sync::atomic::AtomicU64::new(0), +]; + +/// Since the start: slots whose view a newer view of other memory there +/// made stale; ranges of memory noted as mapped, unmapped or written; +/// ranges dropped because no pass took them; slots made due by such +/// ranges; and made slots whose memory was found unmapped (made null). +pub(crate) static STALE: [std::sync::atomic::AtomicU64; 5] = + [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// When a view the title writes makes older views of other memory stale +/// ([`Rule`]): where it starts in the block of their smallest levels, by +/// default; `VICTORY_STALE_TEXTURES=0`: never, as before; +/// `VICTORY_STALE_TEXTURES=overlap`: wherever their spans overlap, the rule +/// until run 188. +fn stale_rule() -> Rule { + static RULE: std::sync::OnceLock = std::sync::OnceLock::new(); + *RULE.get_or_init(|| match std::env::var("VICTORY_STALE_TEXTURES").as_deref() { + Ok("0") => Rule::Never, + Ok("overlap") => Rule::Overlap, + _ => Rule::Start, + }) +} + +/// The runtime mapped or unmapped title memory `[at, at + len)`, or is +/// about to write it through the kernel (`crate::watch`): the placed +/// textures there may have arrived, gone, or changed with no descriptor +/// written. The range is kept for the next texture pass +/// ([`HostHeap::texture_slots_remapped`]). Called with the runtime's own +/// locks held: this locks one mutex of its own and calls nothing. +pub(crate) fn remapped(at: usize, len: usize) { + use std::sync::atomic::Ordering::Relaxed; + /// Ranges kept until a pass takes them. + const MOST: usize = 1 << 15; + let (start, end) = (at as u64, at.saturating_add(len) as u64); + if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) { + return; + } + let mut ranges = REMAPPED.lock().unwrap_or_else(|e| e.into_inner()); + STALE[1].fetch_add(1, Relaxed); + // Pages are mapped one after the other. + if let Some(last) = ranges.last_mut() + && last.1 == start + { + last.1 = end; + return; + } + if ranges.len() >= MOST { + // No pass runs (no shader that picks textures by index is bound): + // the slots there are looked at when they are due, as before. + STALE[2].fetch_add(ranges.len() as u64, Relaxed); + ranges.clear(); + } + ranges.push((start, end)); +} + +/// Frames for which a slot a draw read through a table counts as a table's +/// slot ([`HostHeap::tabled`]). +const TABLED_FRAMES: u64 = 240; + +/// Frames a write of a table's slot waits in the queue for the draw that +/// reads it, before the slot is taken for one shaders pick by index. +/// Frames as `crate::frame::current` counts them: in its opening cutscene +/// The title begins two or three of them per frame it presents +/// (435 begun in the 353 s of run 52's, for some 140 presented). +const TABLED_GRACE: u64 = 8; + +/// In [`HostHeap::tabled`]: a draw read the slot in that frame. +const TABLED_READ: u32 = 1 << 31; + +/// Since the start: writes of texture views into slots that count as a +/// table's (due later), and slots that left the queue because a draw read +/// them through a table. +pub(crate) static TABLED_WRITES: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether slots draws read through tables leave the queue of textures +/// picked by index; `VICTORY_TABLED_TEXTURES=1` keeps them in it as +/// before. +fn tabled_out() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TABLED_TEXTURES").is_none_or(|v| v != "1")) +} + +/// What the queue of textures picked by index knows of a title slot. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Waiting { + /// The frame from which the slot is due. + due: u64, + /// The frame it was written in. + written: u64, + /// Which write of the queue put it here: the pass hands it back with + /// what it did, so a slot written again meanwhile stays as written. + write: u64, + /// Looks in a row that found nothing to upload (its memory not mapped, + /// or no more of it than at the last upload). + looks: u8, + /// Bytes of its memory that were mapped when it was last uploaded + /// without all of it there; 0: not uploaded yet. + mapped: u64, + /// For a slot uploaded whole and looked at again + /// ([`TextureQueue::recheck`]): where its memory is (address, bytes), + /// the fingerprint it had at the upload, how many looks found it + /// unchanged, and the frame of the upload. A fingerprint of 0: none. + checked: (u64, u64, u64, u8, u64), +} + +/// The queue of title slots whose texture view waits to be brought up to +/// date for shaders that pick textures by index: which are due, and in +/// which order (no host heap needed, so it is tested without one). +#[derive(Default)] +pub(crate) struct TextureQueue { + slots: std::collections::BTreeMap, + writes: u64, +} + +impl TextureQueue { + /// A texture view was written into slot `index` in `frame`, due from + /// frame `due`. `seen`: it was not written, a draw or the pass made + /// the host slot from a view the queue may hold already, which then + /// stays as it is. + fn written(&mut self, index: u32, frame: u64, due: u64, seen: bool) { + if seen && self.slots.contains_key(&index) { + return; + } + self.writes += 1; + let write = self.writes; + self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); + } + + fn remove(&mut self, index: u32) { + self.slots.remove(&index); + } + + /// Up to `max` slots due at `frame`, each with its write number, in + /// the order to serve them: + /// - first the ones looked at before (their memory was not mapped, or + /// only part of it): the look is a query, and memory that has + /// arrived since is what the title streamed in last; + /// - then the others, the newest write first and the oldest next, in + /// turns: slot order served the low slots of a backlog of + /// 25,000-40,000 while the textures of the shot on screen waited + /// (run 52: 98% of the drawn pixels had no colour texture in the + /// first 3D frames). + fn due(&self, frame: u64, max: usize) -> Vec<(u32, u64)> { + let mut again: Vec<(u64, u32, u64)> = Vec::new(); + let mut fresh: Vec<(u64, u32, u64)> = Vec::new(); + for (&index, w) in self.slots.iter().filter(|(_, w)| w.due <= frame) { + let class = if w.looks > 0 || w.mapped > 0 { &mut again } else { &mut fresh }; + class.push((w.written, index, w.write)); + } + // By the number of the write, counted over the run. + let newest_first = |a: &(u64, u32, u64), b: &(u64, u32, u64)| b.2.cmp(&a.2); + again.sort_unstable_by(newest_first); + fresh.sort_unstable_by(newest_first); + let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write)| (index, write)).collect(); + let (mut new, mut old) = (0, fresh.len()); + while new < old && order.len() < max { + order.push((fresh[new].1, fresh[new].2)); + new += 1; + if new < old && order.len() < max { + old -= 1; + order.push((fresh[old].1, fresh[old].2)); + } + } + order.truncate(max); + order + } + + /// The entry of `index` if it is still the write the pass was handed. + fn same(&mut self, index: u32, write: u64) -> Option<&mut Waiting> { + self.slots.get_mut(&index).filter(|w| w.write == write) + } + + /// Slot `index` is up to date: out of the queue until written again. + fn done(&mut self, index: u32, write: u64) { + if self.same(index, write).is_some() { + self.slots.remove(&index); + } + } + + /// Nothing to upload at slot `index` now: looked at again after 1, 2, + /// 4, ... frames, at most `most`. + fn later(&mut self, index: u32, write: u64, frame: u64, most: u64) { + if let Some(w) = self.same(index, write) { + w.due = frame + (1u64 << w.looks.min(16)).min(most.max(1)); + w.looks = w.looks.saturating_add(1); + } + } + + /// Slot `index` was uploaded with `mapped` bytes of its memory there, + /// not all of it: looked at again from frame `due`. + fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) { + if let Some(w) = self.same(index, write) { + (w.due, w.looks, w.mapped) = (due, 0, mapped.max(1)); + } + } + + /// Slot `index` was uploaded whole from memory `at` (address, bytes) + /// with fingerprint `print`: looked at again from frame `due`, for a + /// title that fills a texture's memory after it wrote the view (the + /// `looks`-th such look; `uploaded` is the upload's frame). + #[allow(clippy::too_many_arguments)] + fn recheck(&mut self, index: u32, write: u64, due: u64, at: (u64, u64), print: u64, looks: u8, uploaded: u64) { + if let Some(w) = self.same(index, write) { + (w.due, w.looks, w.mapped) = (due, 1, 0); + w.checked = (at.0, at.1, print, looks, uploaded); + } + } + + /// What [`TextureQueue::recheck`] noted of slot `index`, if it is + /// waiting for such a look. + fn checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { + self.slots.get(&index).map(|w| w.checked).filter(|c| c.2 != 0) + } + + /// The memory slot `index`'s texture lies in was mapped, unmapped or + /// written in `frame`: the slot is looked at from frame `due` as one + /// written now, whatever was known of it (a pass at work on it does + /// not take it out). + fn changed(&mut self, index: u32, frame: u64, due: u64) { + self.writes += 1; + let write = self.writes; + let due = self.slots.get(&index).map_or(due, |w| w.due.min(due)); + self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); + } + + /// Bytes of slot `index`'s memory that were mapped at its last upload + /// (0: not uploaded, or all of it was). + fn mapped(&self, index: u32) -> u64 { + self.slots.get(&index).map_or(0, |w| w.mapped) + } + + /// For the frame line: slots in the queue; of them due at `frame`; + /// waiting for their memory (looked at, never uploaded); uploaded in + /// part; and the frames the oldest due one has waited since its write. + fn census(&self, frame: u64) -> [u64; 5] { + let mut c = [self.slots.len() as u64, 0, 0, 0, 0]; + for w in self.slots.values() { + if w.mapped > 0 { + c[3] += 1; + } else if w.looks > 0 { + c[2] += 1; + } + if w.due <= frame { + c[1] += 1; + c[4] = c[4].max(frame.saturating_sub(w.written)); + } + } + c + } +} + +/// Whether `view` is of a texture the title may fill itself: a texture it +/// placed in memory, or a texture object. +pub(crate) fn is_texture_view(view: &View) -> bool { + match view { + View::Placed(false, resource, _) => resource[0] != 1, + View::Shader(r, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_none(), + _ => false, + } +} + +/// Buffer views left null because the host would refuse them +/// ([`buffer_view_ok`]), since the start. +pub(crate) static REFUSED_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether the host device is gone, and why (the first time it is asked +/// after that): for passes that make many views, to name the one that did +/// it. +pub(crate) fn device_removed() -> Option { + let host = host()?; + // SAFETY: a plain query. + let reason = unsafe { host.device.GetDeviceRemovedReason() }; + reason.err().map(|e| e.to_string()) +} + +/// Writes of title view-heap slots with a placed texture view and with a +/// view of a texture object, since the start (diagnostic counts). +pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Bytes per element of a buffer view, as the console's descriptor holds +/// them for indexed reads (structured: the stride; raw: 1, the index is the +/// byte; typed: the format's); `None` if `view` is not a buffer view. +fn view_stride(view: &View) -> Option { + const BUFFER: u32 = 1; + let (words, unordered): (&[u32; 10], bool) = match view { + View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false), + View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true), + View::Placed(unordered, resource, d) if resource[0] == BUFFER => { + (d[..10].try_into().ok()?, *unordered) + } + _ => return None, + }; + // SAFETY: buffer views' union members. + let (stride, raw, format) = unsafe { + if unordered { + let d = uav_desc(words); + let b = d.Anonymous.Buffer; + (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, d.Format) + } else { + let d = srv_desc(words); + let b = d.Anonymous.Buffer; + (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, d.Format) + } + }; + Some(if stride > 0 { + stride + } else if raw { + 1 + } else { + crate::resource::element(format.0 as u32).map_or(0, |(bytes, _)| bytes as u32) + }) } /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for @@ -67,65 +591,13 @@ pub(crate) fn near_heaps(va: u64) -> String { } else if va < start + bytes { format!("inside, slot {}", (va - start) / step) } else { - format!( - "{:#x} past its end (slot {})", - va - start - bytes, - (va - start) / step - ) + format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step) }; text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}")); } text } -/// A GFX10 buffer descriptor's dword 3 for raw access: X Y Z W selects, a -/// 32-bit float format, raw out-of-range checking, resource level 1. The -/// address and size in dwords 0 to 2 are what programs read. -const RAW_DWORD3: u32 = 0x3101_6FAC; - -/// The console words of a descriptor for `view`, as far as programs read -/// them as numbers: a buffer descriptor's address, stride and record count -/// for buffer views, constant buffers and acceleration structures (whose -/// descriptor is a buffer at the structure); zero otherwise. -pub(crate) fn console_words(view: &View) -> [u32; 8] { - let (address, len, stride) = match view { - View::Constant(address, size) => (*address, u64::from(*size), 0), - // An acceleration structure (dimension 11) names no resource: its - // location is the union's first quadword. - View::Shader(0, Some(d)) if d[1] == 11 => ( - u64::from(d[4]) | u64::from(d[5]) << 32, - u64::from(u32::MAX), - 0, - ), - v => match buffer_range(v) { - Some((address, len)) => { - let stride = match v { - View::Shader(_, Some(d)) | View::Unordered(_, _, Some(d)) => d[7], - View::Placed(_, _, d) => d[7], - _ => 0, - }; - (address, len, stride) - } - None => return [0; 8], - }, - }; - let records = if stride > 0 { - len / u64::from(stride) - } else { - len - }; - [ - address as u32, - (address >> 32) as u32 & 0xFFFF | (stride & 0x3FFF) << 16, - records.min(u64::from(u32::MAX)) as u32, - RAW_DWORD3, - 0, - 0, - 0, - 0, - ] -} - /// The host's limit for shader-visible view heaps on resource binding /// tiers 1 and 2; tier 3 hardware may take more. const PORTABLE_VIEWS: u32 = 1_000_000; @@ -182,13 +654,15 @@ pub(crate) fn probe_view_limit() { /// Slots past the title's in a view heap, for tables a draw needs made /// afresh (constant buffers copied per draw). A list holds the slots it /// took until it is reset (its submissions have run) or released. -/// 2^16 ran out seconds into the world (every world run on an RX 9070 XT, -/// each a device removal shortly after; #59). -const DYNAMIC: u32 = 1 << 18; - -/// The dynamic slots of a heap whose host would not take [`DYNAMIC`] more -/// (a capped heap, NVIDIA): the title's slots keep their room first. -const MIN_DYNAMIC: u32 = 1 << 16; +/// 2^16 ran out in the world ("no free dynamic descriptor slots", run 11; +/// upstream PR #336 takes 2^18). On a host heap capped at 1,000,000 views +/// (NVIDIA) these come out of the title's slots, whose highest seen is +/// about 720,000: 2^17 left 868,000 of them, and ran out in the opening +/// cutscene (a frame asks for up to 16,000 tables while the frame before +/// still holds its own; a draw refused its table read slots never made +/// for it, and the card stopped within frames). 2^18 leaves 737,000; a +/// table past them is made afresh in these slots like any other. +pub(crate) const DYNAMIC: u32 = 1 << 18; impl HostHeap { pub(crate) fn new(sampler: bool, count: u32) -> Option { @@ -210,7 +684,7 @@ impl HostHeap { }) } }; - let want = if sampler { 0 } else { DYNAMIC }; + let extra = if sampler { 0 } else { DYNAMIC }; // A view heap ends at the null slot shaders clamp view indices to // (`probe_view_limit`), whatever the title's own count: the title's // slots, then the dynamic ones, then null up to and with that slot. @@ -222,57 +696,26 @@ impl HostHeap { } else { victory_shader::emit::view_heap_limit() }; - let (heap, count, extra, size) = if null == 0 { - // No null slot to clamp to (a sampler heap, or the probe could - // not run): the larger dynamic range only where the host takes - // it on top of every title slot; else the smaller one, and the - // cap after that. - if sampler { - match make(count) { - Ok(heap) => (heap, count, 0, count), - Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); - return None; - } - } - } else if let Ok(heap) = make(count + DYNAMIC) { - (heap, count, DYNAMIC, count + DYNAMIC) - } else { - match make(count + MIN_DYNAMIC) { - Ok(heap) => (heap, count, MIN_DYNAMIC, count + MIN_DYNAMIC), - Err(e) if count + MIN_DYNAMIC > PORTABLE_VIEWS => { - // shortcut: descriptors past the host's limit are left - // out; a title that reaches them needs remapping. - tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); - ( - make(PORTABLE_VIEWS).ok()?, - PORTABLE_VIEWS - MIN_DYNAMIC, - MIN_DYNAMIC, - PORTABLE_VIEWS, - ) - } - Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); - return None; - } + let (heap, count, size) = if null == 0 { + match make(count + extra) { + Ok(heap) => (heap, count, count + extra), + Err(e) => { + tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); + return None; } } } else { let size = null + 1; - let fitted = if count + want <= null { + let fitted = if count + extra <= null { count } else { - // shortcut: descriptors past the host's limit are left out; a - // title that reaches them needs remapping. They read the null - // slot instead. - tracing::warn!( - count, - "host view heap capped at {size}; views past it read a null slot" - ); - null - want + // shortcut: descriptors past the host's limit are left out; a title that reaches + // them needs remapping. They read the null slot instead. + tracing::warn!(count, "host view heap capped at {size}; views past it read a null slot"); + null - extra }; match make(size) { - Ok(heap) => (heap, fitted, want, size), + Ok(heap) => (heap, fitted, size), Err(e) => { tracing::warn!(error = %e, count, size, "no host view heap"); return None; @@ -287,26 +730,6 @@ impl HostHeap { ) }; tracing::debug!(count, sampler, "host descriptor heap"); - // DRED identifies matching allocations by name. Descriptor handles - // have their own increment and cannot locate a faulting GPU VA. - crate::host::name(&heap, || { - let kind = if sampler { "sampler" } else { "view" }; - format!("{kind} descriptor heap ({} slots)", count + extra) - }); - let words = if sampler { - None - } else { - let bytes = u64::from(count + extra) * 32; - host.shared_buffer(bytes).map(|(buffer, data)| { - crate::host::name(&buffer, || format!("descriptor words {count}+{extra}")); - // SAFETY: a fresh mapping of `bytes`; a live buffer. - unsafe { - std::ptr::write_bytes(data, 0, bytes as usize); - let gpu = buffer.GetGPUVirtualAddress(); - (buffer, data as usize, gpu) - } - }) - }; // SAFETY: a live shader-visible heap. let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( @@ -315,20 +738,39 @@ impl HostHeap { u64::from(step), sampler, )); - // With breadcrumbs the last of the dynamic slots is kept for the buffer's UAV. - let crumb = u32::from(!sampler && crate::breadcrumb::enabled()); + let strides = (!sampler) + .then(|| { + let bytes = u64::from(victory_shader::emit::SLOT_STRIDES_COUNT) * 4; + let (buffer, data) = host.upload_buffer(bytes)?; + // SAFETY: the buffer's whole mapping; a live buffer. + let gpu = unsafe { + std::ptr::write_bytes(data, 0, bytes as usize); + buffer.GetGPUVirtualAddress() + }; + crate::host::name(&buffer, || "element strides by view heap slot".to_owned()); + Some((buffer, gpu, data as usize)) + }) + .flatten(); let h = HostHeap { heap, cpu, step, count, - dynamic: extra - crumb, - crumb: crumb == 1, + dynamic: extra, sampler, made: Mutex::new(vec![0; count as usize]), kept: Mutex::new(vec![None; (count + extra) as usize]), - next: Mutex::new((0, vec![false; (extra - crumb) as usize])), - words, + next: Mutex::new((0, vec![false; DYNAMIC as usize])), + free: std::sync::atomic::AtomicU32::new(DYNAMIC), + too_long: std::sync::atomic::AtomicU32::new(u32::MAX), + strides, + buffers: Mutex::default(), + changed: Mutex::default(), + textures: Mutex::default(), + tabled: (0..if sampler { 0 } else { count }) + .map(|_| std::sync::atomic::AtomicU32::new(0)) + .collect(), + placed: Mutex::default(), }; // A slot never written is undefined: shaders reading one (a slot // the title wrote in a way we do not know, or a table entry no @@ -338,13 +780,7 @@ impl HostHeap { if let Err(e) = h.fill_null(kind, size) { tracing::warn!(error = %e, "host descriptor heap not made null"); } - tracing::debug!( - ms = started.elapsed().as_millis(), - "host descriptor heap made null" - ); - if let Some(at) = h.breadcrumb_slot() { - crate::breadcrumb::describe(&host.device, h.cpu(at)); - } + tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null"); Some(h) } @@ -356,12 +792,11 @@ impl HostHeap { // SAFETY: plain heap creation and copies inside live heaps. unsafe { let block: ID3D12DescriptorHeap = - host.device - .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: BLOCK, - ..Default::default() - })?; + host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: BLOCK, + ..Default::default() + })?; let start = block.GetCPUDescriptorHandleForHeapStart(); let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + (i * self.step) as usize, @@ -374,15 +809,13 @@ impl HostHeap { let mut filled = 1; while filled < BLOCK { let n = filled.min(BLOCK - filled); - host.device - .CopyDescriptorsSimple(n, at(filled), start, kind); + host.device.CopyDescriptorsSimple(n, at(filled), start, kind); filled += n; } let mut done = 0; while done < total { let n = BLOCK.min(total - done); - host.device - .CopyDescriptorsSimple(n, self.cpu(done), start, kind); + host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); done += n; } } @@ -396,22 +829,6 @@ impl HostHeap { } } -impl Drop for HostHeap { - fn drop(&mut self) { - #[cfg(feature = "diagnostics")] - { - let retained = self - .kept - .get_mut() - .unwrap_or_else(|e| e.into_inner()) - .iter() - .filter(|slot| slot.is_some()) - .count(); - KEPT_SLOTS.fetch_sub(retained, std::sync::atomic::Ordering::Relaxed); - } - } -} - /// A plain point sampler at `at`. fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; @@ -435,15 +852,21 @@ impl HostHeap { if self.sampler || n == 0 || n > self.dynamic { return None; } + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::DynamicAsked, 1); let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); let (next, taken) = &mut *guard; + let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n + && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed); let n = n as usize; // Search from `next` on, then from the start. let starts = (*next as usize..self.dynamic as usize).chain(0..*next as usize); let mut run = 0; let mut found = None; let mut last = usize::MAX; - for at in starts { + for at in starts.take(if enough { DYNAMIC as usize } else { 0 }) { // A run cannot wrap past the end. if at != last.wrapping_add(1) { run = 0; @@ -456,32 +879,382 @@ impl HostHeap { } } let Some(first) = found else { + if enough { + self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed); + } static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!(n, "no free dynamic descriptor slots: a table is not made") - }); + ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made")); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::DynamicRefused, 1); + add(C::DynamicNs, started.elapsed().as_nanos() as u64); + } return None; }; + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64); taken[first..first + n].fill(true); - *next = ((first + n) % self.dynamic as usize) as u32; + self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); + *next = ((first + n) % DYNAMIC as usize) as u32; Some(self.count + first as u32) } - /// The slot of the breadcrumb buffer's UAV, with breadcrumbs on. - pub(crate) fn breadcrumb_slot(&self) -> Option { - self.crumb.then_some(self.count + self.dynamic) - } - /// The title slots this heap has host slots for; fewer than the title's /// when the host caps its size. pub(crate) fn count(&self) -> u32 { self.count } - /// The dynamic slots past the title's a heap hands tables out of. - #[cfg(test)] - pub(crate) fn dynamic_slots(&self) -> u32 { - self.dynamic + /// The GPU address of the table of element strides by title slot (view + /// heaps). + pub(crate) fn strides_gpu(&self) -> Option { + self.strides.as_ref().map(|s| s.1) + } + + /// The table's buffer, for a list to hold. + pub(crate) fn strides_buffer(&self) -> Option<&ID3D12Resource> { + self.strides.as_ref().map(|s| &s.0) + } + + /// Up to `max` title slots whose texture view is due at `frame`, each + /// with its write number, in the order to serve them + /// ([`TextureQueue::due`]), and the queue's counts + /// ([`TextureQueue::census`]). + pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 5]) { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame)) + } + + /// Every title slot of the queue that is due at `frame`, and whether + /// it was uploaded before (in part, or whole and waiting for another + /// look): for the card accounting line + /// (`crate::resource::card_accounting`). + pub(crate) fn texture_slots_all_due(&self, frame: u64) -> Vec<(u32, bool)> { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures + .slots + .iter() + .filter(|(_, w)| w.due <= frame) + .map(|(&index, w)| (index, w.mapped > 0 || w.checked.2 != 0)) + .collect() + } + + /// The texture view of title slot `index` (as handed out with `write`) + /// was brought up to date: due again from frame `again` (uploaded with + /// that many bytes of its memory there, not all), or not until the + /// slot is written again. + pub(crate) fn texture_slot_done(&self, index: u32, write: u64, again: Option<(u64, u64)>) { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + match again { + Some((frame, mapped)) => textures.partly(index, write, frame, mapped), + None => textures.done(index, write), + } + } + + /// Title slot `index` was uploaded whole: see [`TextureQueue::recheck`]. + #[allow(clippy::too_many_arguments)] + pub(crate) fn texture_slot_recheck( + &self, + index: u32, + write: u64, + due: u64, + at: (u64, u64), + print: u64, + looks: u8, + uploaded: u64, + ) { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures.recheck(index, write, due, at, print, looks, uploaded); + } + + /// See [`TextureQueue::checked`]. + pub(crate) fn texture_slot_checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).checked(index) + } + + /// Nothing to upload at title slot `index` now (its memory is not + /// mapped, or no more of it than before): looked at again after 1, 2, + /// 4, ... frames, at most `most`. + pub(crate) fn texture_slot_later(&self, index: u32, write: u64, frame: u64, most: u64) { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures.later(index, write, frame, most); + } + + /// Bytes of title slot `index`'s memory that were mapped when it was + /// last uploaded in part (0: not uploaded, or whole). + pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).mapped(index) + } + + /// Takes the ranges of title memory the runtime mapped, unmapped or + /// wrote since the last call ([`remapped`]) and makes the slots whose + /// placed texture lies there due from the next frame (by when a write + /// under way has landed): memory that arrived is uploaded, memory that + /// went makes the slot null ([`HostHeap::texture_slot_gone`]), and a + /// texture streamed into the place of another of the same description + /// is uploaded although no descriptor says so. Slots tables read are + /// left to their draws. Returns how many slots it made due. + /// shortcut: the ranges are kept in one place for all heaps; the heap + /// whose pass runs first takes them (a title has one view heap). + pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize { + use std::sync::atomic::Ordering::Relaxed; + let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner())); + if ranges.is_empty() { + return 0; + } + let mut slots: Vec = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + ranges.iter().flat_map(|&(start, end)| placed.slots_in(start, end)).collect() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &slots { + textures.changed(slot, frame, frame + 1); + } + STALE[3].fetch_add(slots.len() as u64, Relaxed); + slots.len() + } + + /// Whether host slot `index` is made from the very record the title + /// has at `handle` now. Its host texture then exists (a slot keeps what + /// it views), so bringing that texture up to date takes no memory of + /// the card. + pub(crate) fn texture_slot_made_from(&self, index: u32, handle: u64) -> bool { + if index >= self.count { + return false; + } + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + let key = u64::from(generation) << 32 | u64::from(i); + if tag != VIEW_TAG { + return false; + } + // And the slot holds a host resource: a slot is also noted as made + // from a view the host could not make (`make` gave nothing, the + // slot is null and keeps nothing). The host copy of such a + // texture is held by no slot, may have been let go, and would be + // made anew here, with the card full. `made` first, then `kept`, + // as `mirror` takes them. + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + made.get(index as usize).is_some_and(|&made| made != 0 && made == key) + && self + .kept + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(index as usize) + .is_some_and(Option::is_some) + } + + /// The memory of the texture title slot `index` views is not mapped + /// (any more): a host slot made from it becomes null again, so that + /// the host copy can be let go (`crate::resource::let_go_idle`; a slot + /// keeps what it views). True if the slot was made. + pub(crate) fn texture_slot_gone(&self, index: u32) -> bool { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + if made.get(index as usize).is_none_or(|&key| key == 0) { + return false; + } + self.unmake(&mut made, index); + STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true + } + + /// Makes host slot `index` null again, as it is before its view is + /// made: a null view of the kind it held. + fn unmake(&self, made: &mut [u64], index: u32) { + let Some(key) = made.get_mut(index as usize).map(std::mem::take) else { + return; + }; + if key == 0 { + return; + } + match view_at(key as u32, (key >> 32) as u32) { + Some(view) => null_for(&view, self.cpu(index)), + None => null_view(self.cpu(index)), + } + self.keep(index, None); + } + + /// Title slot `index` is a table's ([`HostHeap::tabled`]). `read`: a + /// draw read it through the table and brought what it views up to + /// date, so the slot leaves the queue of textures picked by index; the + /// caller makes the host slot in place ([`HostHeap::mirror`]), as the + /// pass would have, for a shader that picks it by index all the same. + pub(crate) fn texture_slot_tabled(&self, index: u32, read: bool) { + self.tabled_in(index, read, crate::frame::current()); + } + + /// [`HostHeap::texture_slot_tabled`] in frame `frame`. + fn tabled_in(&self, index: u32, read: bool, frame: u64) { + use std::sync::atomic::Ordering::Relaxed; + let Some(stamp) = self.tabled.get(index as usize) else { + return; + }; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + let old = stamp.load(Relaxed); + if !read { + if old & !TABLED_READ != now { + stamp.store(now, Relaxed); + } + return; + } + // Once per slot and frame: tables are read by every draw. + if old != now | TABLED_READ { + stamp.store(now | TABLED_READ, Relaxed); + if tabled_out() { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + if textures.slots.remove(&index).is_some() { + TABLED_WRITES[1].fetch_add(1, Relaxed); + } + } + } + } + + /// Whether title slot `index` was a table's within the last + /// [`TABLED_FRAMES`] frames before `frame` (never, if such slots are + /// to be queued as any other). + fn tabled_lately(&self, index: u32, frame: u64) -> bool { + let stamp = self.tabled_stamp(index) & !TABLED_READ; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + tabled_out() && stamp != 0 && u64::from(now.wrapping_sub(stamp)) <= TABLED_FRAMES + } + + /// What `tabled` holds for title slot `index`; 0: never a table's. + fn tabled_stamp(&self, index: u32) -> u32 { + self.tabled + .get(index as usize) + .map_or(0, |s| s.load(std::sync::atomic::Ordering::Relaxed)) + } + + /// The queue's part of a write of title slot `index` in `frame`: + /// `texture`, whether it now holds a view of a texture the title may + /// fill; `seen` as for [`HostHeap::note_buffer`]. + fn queue_texture(&self, index: u32, texture: bool, seen: bool, frame: u64) { + let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 }; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + // A table's slot lately: the draw that reads it uploads its + // texture, so its write waits for that draw. + let lately = stamp != 0 && u64::from(now.wrapping_sub(stamp & !TABLED_READ)) <= TABLED_FRAMES; + // Made now by a draw of this frame that read it through a table: + // up to date. + let read_now = seen && stamp == now | TABLED_READ; + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + if texture && !read_now { + let due = if lately && !seen { + TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + frame + TABLED_GRACE + } else { + 0 + }; + textures.written(index, frame, due, seen); + } else { + textures.remove(index); + } + } + + /// The title slots that hold buffer views. + pub(crate) fn buffer_slots(&self) -> Vec { + let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); + buffers.iter().copied().collect() + } + + /// The title slots whose buffer view was written, or went, since the + /// last call. + pub(crate) fn buffer_changes(&self) -> Vec { + let mut changed = self.changed.lock().unwrap_or_else(|e| e.into_inner()); + std::mem::take(&mut *changed).into_iter().collect() + } + + /// Records what title slot `index` now holds for shaders that pick + /// buffers from the heap: its element stride in the table, and whether + /// it is a buffer view at all. + /// `seen`: the slot was not written now, a draw or a pass made its + /// host slot from what it held. + /// Returns the title slots whose placed texture view the write made + /// stale ([`Spans`]): out of the queue of textures already, their host + /// slots are the caller's to make null (it holds `made`). + fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec { + if self.sampler { + return Vec::new(); + } + // Measured for the texture side of the same gap (textures a shader + // picks by a computed index are neither made, if placed, nor + // uploaded): slots written with a placed texture view, and with a + // view of a texture object. + let texture = match view { + Some(View::Placed(false, resource, _)) if resource[0] != 1 => { + PLACED_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true + } + Some(View::Shader(r, _)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => { + OBJECT_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true + } + _ => false, + }; + self.queue_texture(index, texture, seen, crate::frame::current()); + // The memory a placed texture view describes. Not for a slot + // tables read (thousands of writes a frame, each read by its + // draw): no pass looks at it, and the same texture's view in a + // slot shaders pick by index says what it says. + let placed_view = match view { + Some(View::Placed(false, resource, desc)) + if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) => + { + Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32)) + } + _ => None, + }; + let stale = { + use std::sync::atomic::Ordering::Relaxed; + let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + let span = placed_view + .and_then(|(resource, start)| Some((start, start.saturating_add(placed.bytes(resource)?)))); + match span { + Some((start, end)) => { + SPANNED[0].fetch_min(start, Relaxed); + SPANNED[1].fetch_max(end, Relaxed); + placed.rule = stale_rule(); + placed.note(index, start, end, !seen) + } + None => { + placed.forget(index); + Vec::new() + } + } + }; + if !stale.is_empty() { + STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &stale { + textures.remove(slot); + } + } + let stride = view.and_then(view_stride); + if let Some((_, _, data)) = &self.strides + && index < victory_shader::emit::SLOT_STRIDES_COUNT + { + // SAFETY: inside the mapping; shaders read it while we write (a + // dword, either value is one the slot had). + unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) }; + } + let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); + let was = if stride.is_some() { + buffers.insert(index); + true + } else { + buffers.remove(&index) + }; + if was { + self.changed + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(index); + } + stale } /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] @@ -495,6 +1268,9 @@ impl HostHeap { let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); let end = (at + n).min(self.dynamic) as usize; if let Some(slots) = guard.1.get_mut(at as usize..end) { + let given = slots.iter().filter(|taken| **taken).count() as u32; + self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed); + self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed); slots.fill(false); } } @@ -507,7 +1283,6 @@ impl HostHeap { null_for(view, self.cpu(index)); } self.keep(index, kept.flatten()); - self.write_words(index, console_words(view)); } /// Makes slot `index` read nothing: a null view, or a plain sampler. @@ -518,72 +1293,112 @@ impl HostHeap { null_view(self.cpu(index)); } self.keep(index, None); - self.write_words(index, [0; 8]); } - /// The host GPU address of the heap's descriptor words (view heaps). - pub(crate) fn words(&self) -> Option { - self.words.as_ref().map(|w| w.2) + /// Slot `index` now views `resource` (or nothing of the host's). + fn keep(&self, index: u32, resource: Option) { + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(slot) = kept.get_mut(index as usize) { + // A running submission may still read the old resource through + // this slot. + if let Some(old) = std::mem::replace(slot, resource) { + crate::host::retire(old); + } + } } - fn write_words(&self, index: u32, words: [u32; 8]) { - let Some((_, data, _)) = self.words else { - return; + /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes + /// of `buffer` from byte `offset` (a multiple of 16): a root SRV with a + /// size, whose reads past it return zeros instead of reaching whatever + /// the host placed after the buffer. + pub(crate) fn raw_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { + let Some(host) = host() else { return }; + let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: offset / 4, + NumElements: elements, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, }; - if index >= self.count + self.dynamic { - return; - } - // SAFETY: slot `index` of the mapping, 32 bytes each. + // SAFETY: a slot of our heap and a live buffer covering the range. unsafe { - std::ptr::copy_nonoverlapping( - words.as_ptr(), - (data as *mut u32).add(index as usize * 8), - 8, - ); - } + host.device + .CreateShaderResourceView(buffer, Some(&desc), self.cpu(index)) + }; + self.keep(index, Some(buffer.clone())); + } + + /// Makes slot `index` (a dynamic one) a raw buffer view that reads + /// zeros. + pub(crate) fn null_raw_at(&self, index: u32) { + null_buffer_view(self.cpu(index)); + self.keep(index, None); } /// Makes slot `index` (a dynamic one) a raw unordered access view of - /// `n` dwords of `buffer` from dword `first` on, holding the buffer - /// while the slot does. - pub(crate) fn raw_uav_at(&self, index: u32, buffer: &ID3D12Resource, first: u64, n: u32) { + /// `len` bytes of `buffer` from byte `offset` (a multiple of 16): a + /// root UAV with a size, whose accesses past it do nothing instead of + /// reaching whatever the host placed after the buffer. + pub(crate) fn raw_uav_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { let Some(host) = host() else { return }; + let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32; let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, ViewDimension: D3D12_UAV_DIMENSION_BUFFER, Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Buffer: D3D12_BUFFER_UAV { - FirstElement: first, - NumElements: n, + FirstElement: offset / 4, + NumElements: elements, + StructureByteStride: 0, + CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_RAW, - ..Default::default() }, }, }; - // SAFETY: a slot of our heap and a live buffer. + // SAFETY: a slot of our heap and a live buffer covering the range. unsafe { - host.device - .CreateUnorderedAccessView(buffer, None, Some(&desc), self.cpu(index)) + host.device.CreateUnorderedAccessView( + buffer, + None::<&ID3D12Resource>, + Some(&desc), + self.cpu(index), + ) }; self.keep(index, Some(buffer.clone())); - self.write_words(index, [0; 8]); } - /// Slot `index` now views `resource` (or nothing of the host's). - fn keep(&self, index: u32, resource: Option) { - let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(slot) = kept.get_mut(index as usize) { - #[cfg(feature = "diagnostics")] - if slot.is_some() != resource.is_some() { - use std::sync::atomic::Ordering::Relaxed; - if resource.is_some() { - KEPT_SLOTS.fetch_add(1, Relaxed); - } else { - KEPT_SLOTS.fetch_sub(1, Relaxed); - } - } - *slot = resource; - } + /// Makes slot `index` (a dynamic one) a raw unordered access view of + /// nothing: reads give zeros, writes are dropped. + pub(crate) fn null_raw_uav_at(&self, index: u32) { + self.keep(index, None); + let Some(host) = host() else { return }; + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: 1, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&desc), + self.cpu(index), + ) + }; } /// The shader-visible handle of slot `index`. @@ -595,37 +1410,10 @@ impl HostHeap { } } - /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes - /// of `buffer` from byte `offset` (4-byte units, rounded down), holding - /// the buffer while the slot does. - pub(crate) fn raw_srv_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { - let Some(host) = host() else { return }; - let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { - Format: DXGI_FORMAT_R32_TYPELESS, - ViewDimension: D3D12_SRV_DIMENSION_BUFFER, - Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, - Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { - Buffer: D3D12_BUFFER_SRV { - FirstElement: offset / 4, - NumElements: (len / 4).clamp(1, u64::from(u32::MAX)) as u32, - StructureByteStride: 0, - Flags: D3D12_BUFFER_SRV_FLAG_RAW, - }, - }, - }; - // SAFETY: a live buffer and a slot of our heap; the range lies in it. - unsafe { - host.device - .CreateShaderResourceView(buffer, Some(&desc), self.cpu(index)) - }; - self.keep(index, Some(buffer.clone())); - } - /// Makes slot `index` (a dynamic one) a constant buffer view of host /// memory (the list's own, which it holds). pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { self.keep(index, None); - self.write_words(index, [0; 8]); let Some(host) = host() else { return }; let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, @@ -638,22 +1426,6 @@ impl HostHeap { }; } - /// Makes slot `index` (a dynamic one) a shader resource view of `resource`. - pub(crate) fn srv_at( - &self, - index: u32, - resource: &ID3D12Resource, - desc: &D3D12_SHADER_RESOURCE_VIEW_DESC, - ) { - let Some(host) = host() else { return }; - // SAFETY: a live resource and a slot of our heap. - unsafe { - host.device - .CreateShaderResourceView(resource, Some(desc), self.cpu(index)) - }; - self.keep(index, Some(resource.clone())); - } - fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { D3D12_CPU_DESCRIPTOR_HANDLE { ptr: self.cpu + index as usize * self.step as usize, @@ -691,13 +1463,46 @@ impl HostHeap { if made[index as usize] != 0 { made[index as usize] = 0; self.make_null(index); + let _ = self.note_buffer(index, None, false); + } else if for_draw { + // Left for later and stale since: out of the sets and the stride table. + let _ = self.note_buffer(index, None, false); } return None; }; - // Even buffer views made only for draws have their words now. - self.write_words(index, console_words(&view)); if made[index as usize] != key { - let later = !for_draw && view.is_buffer(); + // Views of other textures in the memory this one describes + // are stale: their host slots read nothing from here on, and + // let go of the host copies they held. + for stale in self.note_buffer(index, Some(&view), for_draw) { + if stale != index { + self.unmake(&mut made, stale); + } + } + // A view of a texture object that has no host copy yet waits + // for it, as buffer views wait for a draw: the slot is made + // when the texture is first used (`super::make_waiting`), or + // here when a draw reads the slot through a table. + let waiting = if for_draw { None } else { view.waiting_texture() }; + if let Some(texture) = waiting { + super::wait_for(texture, handle); + } + let later = !for_draw && (view.is_buffer() || waiting.is_some()); + // Another view of the placed texture the slot shows already (a + // title that streams a texture in writes its view again with + // more mips each time some arrive): the slot goes on showing + // the old view until a draw or the texture pass makes the new + // one and uploads what it shows. Made null here, the texture + // read as nothing for as long as it waited in the queue, every + // time it got sharper. + if later + && keep_views() + && view_at(made[index as usize] as u32, (made[index as usize] >> 32) as u32) + .is_some_and(|old| same_placed_texture(&old, &view)) + { + KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return Some(view); + } made[index as usize] = if later { 0 } else { key }; let kept = if later { None @@ -712,16 +1517,40 @@ impl HostHeap { Some(view) } + /// Whether host slot `index` shows `buffer`; `None` if it shows no + /// resource (diagnostics: a buffer view's slot must show the host copy + /// that is brought up to date for it). + #[cfg(feature = "diagnostics")] + pub(crate) fn shows(&self, index: u32, buffer: &ID3D12Resource) -> Option { + let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + let shown = kept.get(index as usize)?.as_ref()?; + Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer)) + } + + /// What the queue of textures picked by index knows of title slot + /// `index` at `frame`, in a few words (diagnostics). + #[cfg(feature = "diagnostics")] + pub(crate) fn texture_slot_state(&self, index: u32, frame: u64) -> String { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + match textures.slots.get(&index) { + None => "not queued".into(), + Some(w) => format!( + "queued due={} written@{} looks={} part_mapped={} recheck={}", + if w.due <= frame { "now".to_string() } else { format!("@{}", w.due) }, + w.written, + w.looks, + w.mapped, + w.checked.2 != 0 + ), + } + } + /// The view host slot `index` was made from, in a few words, with the /// title and host addresses of a buffer view (diagnostics). "null" for /// a slot never made or left null. #[cfg(feature = "diagnostics")] pub(crate) fn describe_slot(&self, index: u32) -> Option { - let key = *self - .made - .lock() - .unwrap_or_else(|e| e.into_inner()) - .get(index as usize)?; + let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?; if key == 0 { return Some("null".into()); } @@ -813,6 +1642,60 @@ pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> { )) } +/// The title memory the host slot of buffer view `view` is made on +/// (address, bytes): the whole buffer the view is of, which is what +/// [`make`] finds the host copy by. [`buffer_range`] is the part of it the +/// view reads. +pub(crate) fn buffer_extent(view: &View) -> Option<(u64, u64)> { + match view { + View::Shader(r, Some(_)) | View::Unordered(r, _, Some(_)) => { + let (data, len) = crate::resource::buffer_bytes(*r as crate::object::This)?; + Some((data as u64, len)) + } + View::Placed(_, resource, desc) if resource[0] == 1 => Some(( + u64::from(desc[10]) | u64::from(desc[11]) << 32, + u64::from(resource[4]) | u64::from(resource[5]) << 32, + )), + _ => None, + } +} + +/// Whether a buffer view is brought up to date in the host copy its slot +/// shows ([`buffer_copy`]). On by default; `VICTORY_VIEW_EXTENT=0` looks the +/// copy up by the view's range alone, as before. +fn view_extent() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_EXTENT").is_none_or(|v| v != "0")) +} + +/// The host copy buffer view `view` reads, and the title range (address, +/// bytes) it reads there; `None` for other views and empty ranges. +/// +/// The copy is the one the view's slot shows: [`make`] finds it by the +/// whole buffer the view is of ([`buffer_extent`]). Looked up by the range +/// the view reads, as it was, the copy is another one wherever the two +/// lookups differ: for memory outside buffer objects, a view of a part of a +/// buffer that crosses a window line (the buffer's window is two cells, the +/// part's one), and for buffer objects, a part that also lies in a smaller +/// buffer object. The slot then showed a copy nothing brought up to date, +/// and what shaders wrote through it was looked for in the other copy. +pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc, u64, u64)> { + let (address, len) = buffer_range(view)?; + if len == 0 { + return None; + } + if view_extent() + && let Some((base, width)) = buffer_extent(view) + // (The console is lax: a view may begin past its buffer's end.) + && address >= base + && address - base < width.max(1) + && let Some(shadow) = crate::shadow::find(base, width) + { + return Some((shadow, address, len)); + } + crate::shadow::find(address, len).map(|shadow| (shadow, address, len)) +} + /// [`buffer_range`] of an unordered access view of memory at `base`. fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { let desc = uav_desc(words); @@ -831,57 +1714,66 @@ fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { )) } -/// If `view` is a buffer SRV whose offset in its shadow buffer is not a -/// multiple of its element stride (so `FirstElement` cannot address it on the -/// shared shadow buffer), returns `(title_src, byte_len, element_stride, desc)` -/// so the caller can copy the elements into an element-aligned scratch buffer. -pub(crate) fn unaligned_srv( - view: &View, -) -> Option<(u64, u64, u64, D3D12_SHADER_RESOURCE_VIEW_DESC)> { - let (address, len, words): (u64, u64, &[u32; 10]) = match view { - View::Shader(r, Some(words)) => { - if crate::resource::host_resource(*r as crate::object::This).is_some() { - return None; - } - let (data, len) = crate::resource::buffer_bytes(*r as crate::object::This)?; - (data as u64, len, words) - } - View::Placed(false, resource, desc) if resource[0] == 1 => ( - u64::from(desc[10]) | u64::from(desc[11]) << 32, - u64::from(resource[4]) | u64::from(resource[5]) << 32, - desc[..10].try_into().ok()?, - ), - _ => return None, - }; - let mut desc = srv_desc(words); - if desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER { - return None; - } - let element = element_size(&desc); - if element == 0 { - return None; - } - let shadow = crate::shadow::find(address, len)?; - if shadow.offset(address) % element == 0 { - return None; - } - // SAFETY: checked ViewDimension == BUFFER. - let buffer = unsafe { &mut desc.Anonymous.Buffer }; - let first_bytes = buffer.FirstElement.checked_mul(element)?; - let avail = len.saturating_sub(first_bytes); - let max_elems = (avail / element).min(u64::from(u32::MAX)) as u32; - if buffer.NumElements > max_elems { - buffer.NumElements = max_elems; - } - let bytes = u64::from(buffer.NumElements) * element; - if bytes == 0 { +/// The host resource a slot made by [`make`] views, if any. +type Kept = Option; + +/// A structured buffer view (`first`, `count` elements of `stride` bytes, +/// `offset` bytes into its host copy) as a raw view of the same bytes: +/// its first dword and its dwords. Translated shaders read untyped buffers +/// as raw bytes at `element * stride + offset` (the stride from the +/// used-resource entry, or from the table by heap slot for a buffer picked +/// by index), and a raw read through a structured view gives zeros on +/// NVIDIA (reported upstream with PR #193; structured reads through raw +/// views were right there). So the host's view is raw whenever it can be: +/// the bytes must start on 16 (the host's raw view alignment) and be whole +/// dwords. A view that cannot stays structured. +fn raw_window(offset: u64, first: u64, count: u32, stride: u32) -> Option<(u64, u32)> { + if stride == 0 { return None; } - Some((address + first_bytes, bytes, element, desc)) + let start = first.checked_mul(u64::from(stride))?.checked_add(offset)?; + let bytes = u64::from(count) * u64::from(stride); + (start % 16 == 0 && bytes % 4 == 0) + .then(|| u32::try_from(bytes / 4).ok().map(|dwords| (start / 4, dwords))) + .flatten() } -/// The host resource a slot made by [`make`] views, if any. -type Kept = Option; +/// Whether the host accepts a buffer view with these fields of a buffer of +/// `width` bytes. It removes the device for one it does not (view creation +/// returns nothing), and the console is laxer: the title's heap holds +/// views past their memory's end, of no elements, of typeless formats +/// without the raw flag, with strides the host has no structured buffers +/// for. Since every buffer view of the heap is made for shaders that pick +/// them by index, one such view ended the run (2026-11-24, run 10). +fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> bool { + use crate::resource::family; + let f = format.0 as u32; + let element = if raw { + // raw: R32 typeless, counted in dwords, starting on 16 bytes + if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || !first.is_multiple_of(4) { + return false; + } + 4 + } else if stride > 0 { + // structured: no format, a stride the host takes + if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || !stride.is_multiple_of(4) { + return false; + } + u64::from(stride) + } else { + // typed: a format with a size that is not typeless + let typeless = family(f) == f && family(f + 1) == f; + match crate::resource::element(f) { + Some((bytes, 1)) if f != 0 && !typeless && bytes > 0 => bytes, + _ => return false, + } + }; + count > 0 + && first + .checked_add(u64::from(count)) + .and_then(|end| end.checked_mul(element)) + .is_some_and(|end| end <= width) +} fn buffer_srv( address: u64, @@ -890,19 +1782,57 @@ fn buffer_srv( at: D3D12_CPU_DESCRIPTOR_HANDLE, ) -> Option { let shadow = crate::shadow::find(address, len)?; + let offset = shadow.offset(address); + // A structured view as a raw view of the same bytes (see `raw_window`). + // SAFETY: a buffer view's union member. + let structured = unsafe { desc.Anonymous.Buffer }; + let window = (desc.Format == DXGI_FORMAT_UNKNOWN) + .then(|| raw_window(offset, structured.FirstElement, structured.NumElements, structured.StructureByteStride)) + .flatten(); + if let Some((first, count)) = window { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer = D3D12_BUFFER_SRV { + FirstElement: first, + NumElements: count, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }; + } let element = element_size(&desc); // SAFETY: a buffer view's union member. let buffer = unsafe { &mut desc.Anonymous.Buffer }; - let offset = shadow.offset(address); - if element == 0 || offset % element != 0 { + if window.is_none() { + if element == 0 || offset % element != 0 { + once!( + offset, + element, + "buffer view not on an element of its host copy" + ); + return None; + } + buffer.FirstElement += offset / element; + } + let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); + let raw = buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; + // SAFETY: a live buffer. + let width = unsafe { shadow.buffer.GetDesc() }.Width; + if !buffer_view_ok(desc.Format, first, count, stride, raw, width) { + REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); once!( - offset, - element, - "buffer view not on an element of its host copy" + format = desc.Format.0, + first, + count, + stride, + raw, + width, + "buffer view the host would refuse left null" ); return None; } - buffer.FirstElement += offset / element; + // The console has no component mapping; one the host does not know is the default's. + if desc.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING { + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + } let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { @@ -940,25 +1870,50 @@ fn buffer_uav( crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) }; let offset = shadow.offset(address); - if element == 0 || offset % element != 0 { + // A structured view as a raw view of the same bytes (see `raw_window`). + let window = (desc.Format == DXGI_FORMAT_UNKNOWN) + .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride)) + .flatten(); + if let Some((first, count)) = window { + buffer.FirstElement = first; + buffer.NumElements = count; + buffer.StructureByteStride = 0; + buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + } else { + if element == 0 || offset % element != 0 { + once!(offset, element, "unordered buffer view not on an element of its host copy"); + return None; + } + buffer.FirstElement += offset / element; + } + buffer.CounterOffsetInBytes = 0; + let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); + let raw = buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; + if window.is_some() { + // (Left out at first: every structured unordered access view was then + // refused by `buffer_view_ok` and left null, runs 15 and 16.) + desc.Format = DXGI_FORMAT_R32_TYPELESS; + } + // SAFETY: a live buffer. + let width = unsafe { shadow.buffer.GetDesc() }.Width; + if !buffer_view_ok(desc.Format, first, count, stride, raw, width) { + REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); once!( - offset, - element, - "unordered buffer view not on an element of its host copy" + format = desc.Format.0, + first, + count, + stride, + raw, + width, + "unordered buffer view the host would refuse left null" ); return None; } - buffer.FirstElement += offset / element; - buffer.CounterOffsetInBytes = 0; let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { - host.device.CreateUnorderedAccessView( - &shadow.buffer, - None::<&ID3D12Resource>, - Some(&desc), - at, - ) + host.device + .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) }; Some(Some(shadow.buffer.clone())) } @@ -982,6 +1937,9 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere }; let own = d.Format.0 as u32; if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) { + if unordered { + crate::resource::DEPTH_UNORDERED[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } once!( unordered, format = own, @@ -1004,6 +1962,14 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere if view == 0 { return !typeless; } + // A view of a target whose format the host refuses, in the title's + // format: in the stand-in the host copy has. + if view != own && crate::resource::target_format(view) == own { + if let Some(format) = format { + *format = d.Format; + } + return true; + } if family(view) != family(own) { once!(view, own, "view format of another family"); return false; @@ -1016,125 +1982,71 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere true } -/// Re-bases a console SRV mip window onto a host texture whose top `drop` -/// mips were omitted (`host_mips` surviving levels, console levels -/// `drop..drop + host_mips`). -fn rebase_mip_window( - most_detailed: u32, - mip_levels: u32, - min_lod: f32, - drop: u32, - host_mips: u32, -) -> (u32, u32, f32) { - if drop == 0 { - return (most_detailed, mip_levels, min_lod); - } - let host_mips = host_mips.max(1); - let title_mips = host_mips.saturating_add(drop); - let min_lod = (min_lod - drop as f32).max(0.0); - if mip_levels == u32::MAX { - let start = most_detailed.saturating_sub(drop).min(host_mips - 1); - return (start, u32::MAX, min_lod); - } - let end = most_detailed.saturating_add(mip_levels).min(title_mips); - let start = most_detailed.max(drop); - if start < end { - (start - drop, end - start, min_lod) - } else { - // A view naming only dropped mips stays valid at the first surviving - // mip; one past the chain uses the smallest survivor. - let start = if most_detailed < drop { - 0 - } else { - host_mips - 1 +/// The title's unordered access view of a depth texture, as a view of the +/// texture's colour twin `twin` ([`crate::resource::Twin`]): the same mip +/// and slices, in the colour format of the twin's family for a depth or +/// typeless format (R16_UNORM for 16-bit depth, R32_FLOAT for 32-bit; the +/// bits are the same). Without a description: mip 0 of every slice. +/// The twin of a stencil plane (R8) stands for the views of that plane +/// only, which become R8_UINT views of its one plane; `None` for a view of +/// the depth plane, which the twin does not stand for. The depth plane has +/// a twin of its own, viewed as a depth texture's without stencil: a view +/// in the format of the depth plane of a depth-stencil format (21, 46) +/// takes the twin's colour format too. +fn twin_uav( + twin: &ID3D12Resource, + desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, +) -> Option { + // SAFETY: a live resource. + let d = unsafe { twin.GetDesc() }; + let mut desc = desc.cloned().unwrap_or_else(|| { + let mut all = D3D12_UNORDERED_ACCESS_VIEW_DESC { + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() }; - (start, 1, min_lod) - } -} - -/// Adjusts an explicit SRV description for a texture whose top `drop` mips -/// were omitted on the host. -fn adjust_srv_for_mip_drop(srv: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, drop: u32, host_mips: u32) { - if drop == 0 { - return; - } - // SAFETY: each branch reads and writes only the union arm named by - // `srv.ViewDimension`. - unsafe { - match srv.ViewDimension { - D3D12_SRV_DIMENSION_TEXTURE1D => { - let t = &mut srv.Anonymous.Texture1D; - (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( - t.MostDetailedMip, - t.MipLevels, - t.ResourceMinLODClamp, - drop, - host_mips, - ); - } - D3D12_SRV_DIMENSION_TEXTURE1DARRAY => { - let t = &mut srv.Anonymous.Texture1DArray; - (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( - t.MostDetailedMip, - t.MipLevels, - t.ResourceMinLODClamp, - drop, - host_mips, - ); - } - D3D12_SRV_DIMENSION_TEXTURE2D => { - let t = &mut srv.Anonymous.Texture2D; - (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( - t.MostDetailedMip, - t.MipLevels, - t.ResourceMinLODClamp, - drop, - host_mips, - ); - } - D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { - let t = &mut srv.Anonymous.Texture2DArray; - (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( - t.MostDetailedMip, - t.MipLevels, - t.ResourceMinLODClamp, - drop, - host_mips, - ); - } - D3D12_SRV_DIMENSION_TEXTURE3D => { - let t = &mut srv.Anonymous.Texture3D; - (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( - t.MostDetailedMip, - t.MipLevels, - t.ResourceMinLODClamp, - drop, - host_mips, - ); - } - D3D12_SRV_DIMENSION_TEXTURECUBE => { - let t = &mut srv.Anonymous.TextureCube; - (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( - t.MostDetailedMip, - t.MipLevels, - t.ResourceMinLODClamp, - drop, - host_mips, - ); + if d.DepthOrArraySize > 1 { + all.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + all.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { + ArraySize: u32::from(d.DepthOrArraySize), + ..Default::default() + }; + } + all + }); + // A stencil plane's twin (R8 typeless, 60): the title's view is of the + // stencil plane if it names plane 1 or a stencil view format (22, 47). + if d.Format.0 == 60 { + let mut plane = 0; + match desc.ViewDimension { + D3D12_UAV_DIMENSION_TEXTURE2D => { + // SAFETY: the member the dimension names. + let mut view = unsafe { desc.Anonymous.Texture2D }; + plane = std::mem::take(&mut view.PlaneSlice); + desc.Anonymous.Texture2D = view; } - D3D12_SRV_DIMENSION_TEXTURECUBEARRAY => { - let t = &mut srv.Anonymous.TextureCubeArray; - (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( - t.MostDetailedMip, - t.MipLevels, - t.ResourceMinLODClamp, - drop, - host_mips, - ); + D3D12_UAV_DIMENSION_TEXTURE2DARRAY => { + // SAFETY: the member the dimension names. + let mut view = unsafe { desc.Anonymous.Texture2DArray }; + plane = std::mem::take(&mut view.PlaneSlice); + desc.Anonymous.Texture2DArray = view; } _ => {} } + if plane != 1 && !matches!(desc.Format.0, 22 | 47) { + return None; + } + desc.Format.0 = 62; + return Some(desc); } + // None, typeless and depth formats (R16: 0, 53, 55; R32: 0, 39, 40), + // and those of a depth-stencil format's depth plane (19 to 21, 44 to + // 46), for the twin of such a plane. + desc.Format.0 = match (desc.Format.0, d.Format.0) { + (0 | 53 | 55 | 19..=21 | 44..=46, 53) => 56, + (0 | 39 | 40 | 19..=21 | 44..=46, 39) => 41, + (other, _) => other, + }; + Some(desc) } /// Makes the host descriptor for `view` at `at`: the host resource it @@ -1192,10 +2104,6 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { return None; } - let (drop, host_mips) = crate::resource::host_mip_info(resource); - if let Some(srv) = desc.as_mut() { - adjust_srv_for_mip_drop(srv, drop, host_mips); - } // SAFETY: a live texture and a slot of our heap. unsafe { device.CreateShaderResourceView( @@ -1223,7 +2131,37 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { _ => None, }; }; + // The first such views of depth textures are logged as the + // title describes them (format, dimension, then mip, slices and + // plane): they say which planes shaders write, and as what. + if crate::resource::depth_and_unordered(resource) { + static LOGGED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 512 { + tracing::info!( + ?resource, + view = ?desc, + "unordered access view of a depth texture" + ); + } + } let mut desc = desc.as_ref().map(uav_desc); + // A depth texture's unordered access is its colour twin's: the + // host gives a depth texture none. + let twin = crate::resource::twin_resource(resource) + .and_then(|twin| Some((twin, twin_uav(twin, desc.as_ref())?))) + // A view of the depth plane of a texture with a stencil + // plane: of that plane's own twin. + .or_else(|| { + let twin = crate::resource::twin_plane_resource(resource)?; + Some((twin, twin_uav(twin, desc.as_ref())?)) + }); + let texture = match twin { + Some((twin, view)) => { + desc = Some(view); + twin + } + None => texture, + }; if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { return None; } @@ -1264,10 +2202,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { // shortcut: unordered access to a texture the title placed // itself is not mirrored; give it a resource as shader // views of such textures get when a dispatch writes one. - once!( - dimension = resource[0], - "placed unordered texture view not mirrored" - ); + once!(dimension = resource[0], "placed unordered texture view not mirrored"); return None; } // The resource description's width, after the alignment. @@ -1283,6 +2218,30 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { } } +/// Writes of a slot with another view of the placed texture it showed, +/// since the start: the slot kept showing the old view. +pub(crate) static KEPT_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether a slot written with another view of the placed texture it +/// shows keeps showing the old one until the new is made; +/// `VICTORY_KEEP_VIEWS=0` makes it null at once, as before. +fn keep_views() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0")) +} + +/// Whether both are shader views of one texture the title placed in +/// memory: the same address and the same resource description, whatever +/// part of it each shows. +fn same_placed_texture(a: &View, b: &View) -> bool { + match (a, b) { + (View::Placed(false, resource, desc), View::Placed(false, other, other_desc)) => { + resource[0] != 1 && resource == other && desc[10..12] == other_desc[10..12] + } + _ => false, + } +} + /// 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 { @@ -1490,6 +2449,32 @@ mod tests { assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D); } + /// Views of one placed texture are told from views of others by the + /// address and the resource description, not by what they show. + #[test] + fn views_of_one_placed_texture_are_told_by_address_and_description() { + let texture = [3, 0, 0, 0, 512, 0, 512, 0x8_0001, 98, 1, 0, 0x105, 0, 0]; + let view = |resource: [u32; 14], first_mip: u32, address: u32| { + let mut desc = [0u32; 16]; + (desc[0], desc[1], desc[4], desc[5], desc[10], desc[11]) = (98, 4, first_mip, 8 - first_mip, address, 0xb); + View::Placed(false, resource, desc) + }; + let low = view(texture, 3, 0x1000_0000); + // more mips of the same texture + assert!(same_placed_texture(&low, &view(texture, 0, 0x1000_0000))); + // another address, another description, a buffer, an unordered view + assert!(!same_placed_texture(&low, &view(texture, 3, 0x2000_0000))); + let mut wider = texture; + wider[4] = 1024; + assert!(!same_placed_texture(&low, &view(wider, 3, 0x1000_0000))); + let mut buffer = texture; + buffer[0] = 1; + assert!(!same_placed_texture(&view(buffer, 3, 0x1000_0000), &view(buffer, 3, 0x1000_0000))); + let View::Placed(_, resource, desc) = low.clone() else { unreachable!() }; + assert!(!same_placed_texture(&low, &View::Placed(true, resource, desc))); + assert!(!same_placed_texture(&low, &View::Shader(0, None))); + } + /// A null 3D UAV made on the real device leaves it alive. #[test] fn null_3d_uav_is_accepted_by_the_device() { @@ -1506,6 +2491,292 @@ mod tests { } /// Dynamic slots stay taken until given back, and runs do not wrap. + #[test] + fn a_structured_view_made_raw_passes_the_host_check() { + // 100 elements of 20 bytes from element 8, in a copy that starts 32 + // bytes before the view's memory: bytes 192..2192. + let (first, count) = raw_window(32, 8, 100, 20).unwrap(); + assert_eq!((first, count), (48, 500)); + assert!(buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 4096)); + // the format a raw view must name; the structured one's is refused + assert!(!buffer_view_ok(DXGI_FORMAT_UNKNOWN, first, count, 0, true, 4096)); + // past the buffer, not on 16 bytes, no elements + assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 2000)); + assert!(raw_window(4, 0, 100, 20).is_none()); + assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, 0, 0, 0, true, 4096)); + // a structured view the host takes as it is + assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096)); + } + + /// The queue of textures picked by index serves the slots looked at + /// before first, then the newest write and the oldest in turns; a + /// slot whose memory is not there is looked at again after + /// 1, 2, 4 frames up to the limit; and what the pass reports about a + /// slot written again meanwhile is dropped. + #[test] + fn the_texture_queue_serves_the_newest_writes_first() { + let mut q = TextureQueue::default(); + // Slots 10..18 written in frames 1..9, slot 5 last. + for i in 0..8u32 { + q.written(10 + i, u64::from(i) + 1, 0, false); + } + q.written(5, 9, 0, false); + let order: Vec = q.due(9, 100).into_iter().map(|d| d.0).collect(); + // newest, oldest, newest, oldest, and so on + assert_eq!(order, [5, 10, 17, 11, 16, 12, 15, 13, 14]); + assert_eq!(q.due(9, 2).len(), 2); + assert_eq!(q.census(9), [9, 9, 0, 0, 8]); + // Slot 17's memory is not mapped: again next frame, then in 2, 4, 4. + let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1; + let w17 = write(&q, 17); + let mut frame = 9; + for wait in [1, 2, 4, 4] { + q.later(17, w17, frame, 4); + assert!(!q.due(frame + wait - 1, 100).iter().any(|d| d.0 == 17)); + frame += wait; + // Due again, and ahead of every slot never looked at. + assert_eq!(q.due(frame, 100)[0].0, 17); + } + assert_eq!(q.census(9)[2], 1); + q.done(17, w17); + assert!(!q.due(u64::MAX, 100).iter().any(|d| d.0 == 17)); + // Uploaded with part of its memory there: kept, with what was there. + let w16 = write(&q, 16); + q.partly(16, w16, 12, 4096); + assert_eq!(q.mapped(16), 4096); + assert_eq!(q.due(12, 100)[0].0, 16); + // The title writes slot 16 again while the pass works on it: what + // the pass then says about the old write changes nothing. + q.written(16, 13, 0, false); + q.done(16, w16); + q.later(16, w16, 13, 4); + assert_eq!(q.mapped(16), 0); + assert_eq!(q.due(13, 100)[0].0, 16); + // A draw that makes the host slot (`seen`) keeps what the queue knows, + let w15 = write(&q, 15); + q.partly(15, w15, 20, 8192); + q.written(15, 14, 0, true); + assert_eq!(q.mapped(15), 8192); + // and queues a slot the queue did not hold. + q.written(99, 14, 0, true); + assert!(q.due(14, 100).iter().any(|d| d.0 == 99)); + // A write due later (a table's slot) is not handed out before. + q.written(98, 14, 16, false); + assert!(!q.due(15, 100).iter().any(|d| d.0 == 98)); + assert!(q.due(16, 100).iter().any(|d| d.0 == 98)); + } + + /// Textures of which only the smallest levels are held, packed into + /// one another's address range (the three of run 188: 0x2c000 bytes + /// each at full size, their starts 0x2000 and 0x4000 apart): writing + /// any of them, in any order and again, leaves the others. + #[test] + fn packed_neighbours_stay() { + let mut spans = Spans::default(); + assert_eq!(spans.rule, Rule::Start); + let at = 0xb_86bf_8000u64; + let (a, b, c) = (at, at + 0x2000, at + 0x6000); + assert!(spans.note(105_998, a, a + 0x2c000, true).is_empty()); + assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty()); + assert!(spans.note(108_521, c, c + 0x2c000, true).is_empty()); + // The first written again (as a title does when levels arrive), + // from another slot too: its span reaches over the other two. + assert!(spans.note(7, a, a + 0x2c000, true).is_empty()); + assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty()); + let mut all = spans.slots_in(0, u64::MAX); + all.sort_unstable(); + assert_eq!(all, [7, 105_998, 106_004, 108_521]); + // A draw makes a slot of the second texture: it is one of them. + assert!(spans.note(9, b, b + 0x2c000, false).is_empty()); + assert_eq!(spans.by_slot.get(&9), Some(&b)); + } + + /// A texture written where another starts replaces it: at the same + /// address with another length, or inside the block of its smallest + /// levels. The packed neighbours of the one replaced stay. + #[test] + fn a_texture_written_at_the_start_of_another_replaces_it() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + // Another length from the same start: slot 1 is stale, slot 2 not. + assert_eq!(spans.note(3, at, at + 0xb000, true), [1]); + // A start inside the first 4 KiB of slot 3's texture: stale too. + assert_eq!(spans.note(4, at + 0x800, at + 0x1800, true), [3]); + // And the other way: a texture that starts just before one. + assert_eq!(spans.note(5, at + 0x1800, at + 0x4800, true), [2]); + let mut left = spans.slots_in(0, u64::MAX); + left.sort_unstable(); + assert_eq!(left, [4, 5]); + // Exactly 4 KiB apart: both there. + assert!(spans.note(6, at + 0x2800, at + 0x3800, true).is_empty()); + // A draw's view that clashes is left out, and nothing is stale. + assert!(spans.note(8, at + 0x900, at + 0x2900, false).is_empty()); + assert_eq!(spans.by_slot.get(&8), None); + assert_eq!(spans.by_slot.len(), 3); + } + + /// A slot written with another texture leaves its old span; the same + /// view written again changes nothing. + #[test] + fn a_slot_rewritten_moves_to_its_new_span() { + let mut spans = Spans::default(); + assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty()); + assert!(spans.note(2, 0x12000, 0x3e000, true).is_empty()); + assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty()); + assert_eq!(spans.slots_in(0x10000, 0x10001), [1]); + // Slot 1 now views a texture far away. + assert!(spans.note(1, 0x90000, 0x91000, true).is_empty()); + assert_eq!(spans.slots_in(0x10000, 0x10001), [] as [u32; 0]); + assert_eq!(spans.slots_in(0x12000, 0x12001), [2]); + assert_eq!(spans.slots_in(0x90000, 0x90001), [1]); + spans.forget(1); + spans.forget(2); + assert!(spans.by_start.is_empty() && spans.by_slot.is_empty()); + } + + /// Memory the runtime maps, unmaps or writes names the textures that + /// are there: among packed neighbours the one whose held levels the + /// range lies in (it ends where the next one starts), and the ones + /// that start inside the range. + #[test] + fn memory_changed_under_packed_neighbours_names_the_ones_there() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty()); + // Inside the first one's held levels. + assert_eq!(spans.slots_in(at + 0x1000, at + 0x2000), [1]); + // Inside the second's: not the first, which ends where it starts. + assert_eq!(spans.slots_in(at + 0x3000, at + 0x4000), [2]); + // Past the last start: the last one. + assert_eq!(spans.slots_in(at + 0x20000, at + 0x21000), [3]); + // A range over all of them. + assert_eq!(spans.slots_in(at, at + 0x8000), [1, 2, 3]); + // Past the end of all: none. + assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]); + } + + /// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that + /// overlaps others is left out of the spans, as before. + #[test] + fn never_stale_leaves_overlapping_views_out() { + let mut spans = Spans { rule: Rule::Never, ..Default::default() }; + assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(2, 0x2000, 0x4000, true).is_empty()); + assert!(spans.note(3, 0x1000, 0x2000, true).is_empty()); + assert_eq!(spans.slots_in(0, u64::MAX), [1]); + } + + /// The rule until run 188 (`VICTORY_STALE_TEXTURES=overlap`): a view + /// written over memory that older views describe otherwise makes + /// those stale; views of the same span are one texture's. + #[test] + fn a_newer_view_of_other_memory_makes_the_older_stale() { + let mut spans = Spans { rule: Rule::Overlap, ..Default::default() }; + // Three textures side by side, the first in two slots. + assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(3, 0x3000, 0x4000, true).is_empty()); + assert!(spans.note(4, 0x8000, 0x9000, true).is_empty()); + // The same slot written with the same span again: nothing changes. + assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); + assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]); + assert_eq!(spans.slots_in(0x4000, 0x8000), [] as [u32; 0]); + // A draw makes a slot whose view overlaps them: left out, nothing stale. + assert!(spans.note(9, 0x2000, 0x3800, false).is_empty()); + assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]); + // The title writes a texture over the end of the first and all of + // the second: their three slots are stale. + let mut stale = spans.note(5, 0x2000, 0x4000, true); + stale.sort_unstable(); + assert_eq!(stale, [1, 2, 3]); + assert_eq!(spans.slots_in(0, u64::MAX), [5, 4]); + // Another start in the same memory: stale in turn. Another length + // from the same start too. + assert_eq!(spans.note(6, 0x2800, 0x3000, true), [5]); + assert_eq!(spans.note(7, 0x2800, 0x2c00, true), [6]); + // A slot that moves to another texture leaves its span behind. + assert!(spans.note(7, 0x8000, 0x9000, true).is_empty()); + assert_eq!(spans.slots_in(0x2800, 0x2c00), [] as [u32; 0]); + assert_eq!(spans.slots_in(0x8000, 0x8001), [4, 7]); + spans.forget(4); + spans.forget(7); + assert!(spans.by_start.is_empty() && spans.by_slot.is_empty()); + } + + /// Memory the runtime maps under a slot's texture makes the slot due + /// again from the next frame; a stale slot leaves the queue. + #[test] + fn remapped_memory_makes_its_texture_slots_due() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + // 64x64 BC7, one mip, at an address no test and no title uses. + let at = 0x7fee_0000_0000u64; + let view = |address: u64, width: u32| { + let mut desc = [0u32; 16]; + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + View::Placed(false, [3, 0, 0, 0, width, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc) + }; + let len = crate::resource::placed_bytes(&[3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0]).unwrap(); + assert!(heap.note_buffer(1, Some(&view(at, 64)), false).is_empty()); + let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; + assert_eq!(queued, 1); + heap.texture_slot_done(1, write, None); + assert_eq!(slots(u64::MAX), []); + // Memory elsewhere: nothing. Under the texture: due from the next frame. + remapped((at + 2 * len) as usize, 0x1000); + remapped(at as usize, 0x1000); + assert_eq!(heap.texture_slots_remapped(50), 1); + assert_eq!(slots(50), []); + assert_eq!(slots(51), [1]); + // A wider texture written at the same address: slot 1 is stale. + assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [1]); + assert_eq!(slots(u64::MAX), [2]); + } + + /// A slot a draw read through a table leaves the queue; the title's + /// next write of it waits for its draw, and is due after the grace + /// frames if none reads it. + #[test] + fn slots_read_through_tables_leave_the_texture_queue() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let frame = 100; + let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + let texture = View::Placed(false, [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 28, 1, 0, 0x105, 0, 0], [0; 16]); + assert!(is_texture_view(&texture)); + heap.queue_texture(2, true, false, frame); + heap.queue_texture(3, true, false, frame); + assert_eq!(slots(frame), [3, 2]); + heap.tabled_in(3, true, frame); + assert_eq!(slots(frame), [2]); + // Made in place by the draw that read it: still out. + heap.queue_texture(3, true, true, frame); + assert_eq!(slots(frame), [2]); + // Written again in the next frame: due once the grace frames have + // passed without a draw that reads it. + heap.queue_texture(3, true, false, frame + 1); + assert_eq!(slots(frame + TABLED_GRACE), [2]); + assert_eq!(slots(frame + 1 + TABLED_GRACE), [3, 2]); + // The draw comes after all: out again. + heap.tabled_in(3, true, frame + 1); + assert_eq!(slots(u64::MAX), [2]); + // A slot of a table no draw read stays queued; its next write waits. + heap.tabled_in(2, false, frame + 1); + assert_eq!(slots(frame + 1), [2]); + heap.queue_texture(2, true, false, frame + 2); + assert_eq!(slots(frame + 2), []); + // Long after the last table, a write is due at once. + heap.queue_texture(2, true, false, frame + 3 + TABLED_FRAMES); + assert_eq!(slots(frame + 3 + TABLED_FRAMES), [2]); + } + #[test] fn dynamic_slots_are_held_until_released() { let Some(heap) = HostHeap::new(false, 4) else { @@ -1520,54 +2791,4 @@ mod tests { assert_eq!(heap.dynamic(50), Some(4)); assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } - - /// A placed structured buffer SRV whose offset in its shadow buffer is not - /// a multiple of its stride is flagged for element-aligned copying. - #[test] - fn unaligned_buffer_srv_is_detected() { - if host().is_none() { - return; // no host GPU - } - let start = 0x7000_0000u64; - let resource_id = 0xDEAD_BEEF_usize; - crate::shadow::register(resource_id, start, 4096); - - let placed = |addr: u64, num_elements: u32, stride: u32| { - let mut res = [0u32; 14]; - res[0] = 1; // BUFFER - res[4] = num_elements * stride; - let mut desc = [0u32; 16]; - desc[1] = 1; // D3D12_SRV_DIMENSION_BUFFER - desc[2] = 5768; // default component mapping - desc[6] = num_elements; - desc[7] = stride; - desc[10] = addr as u32; - desc[11] = (addr >> 32) as u32; - View::Placed(false, res, desc) - }; - - // Offset 112 is a multiple of stride 56 -> aligned on the shadow buffer. - assert!(unaligned_srv(&placed(start + 112, 2, 56)).is_none()); - - // Offset 16 is not a multiple of stride 56 -> must be copied aligned. - let (src, bytes, align, desc) = - unaligned_srv(&placed(start + 16, 2, 56)).expect("unaligned"); - assert_eq!((src, bytes, align), (start + 16, 112, 56)); - // SAFETY: checked BUFFER dimension. - assert_eq!(unsafe { desc.Anonymous.Buffer.NumElements }, 2); - - crate::shadow::unregister(resource_id, start); - } - - #[test] - fn srv_mip_window_rebasing_handles_partial_full_and_dropped_ranges() { - assert_eq!(rebase_mip_window(1, 3, 3.5, 2, 5), (0, 2, 1.5)); - assert_eq!(rebase_mip_window(3, 2, 1.0, 2, 5), (1, 2, 0.0)); - assert_eq!( - rebase_mip_window(0, u32::MAX, 0.0, 2, 5), - (0, u32::MAX, 0.0) - ); - assert_eq!(rebase_mip_window(0, 1, 0.0, 2, 5), (0, 1, 0.0)); - assert_eq!(rebase_mip_window(1, 3, 1.5, 0, 7), (1, 3, 1.5)); - } } diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index cce7ed2..dfbf2b2 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -29,7 +29,7 @@ pub static IID: Iid = guid( ); /// The levels the device answers to, as on PC: `ID3D12Device1` to -/// `ID3D12Device8`, and `ID3D12Device11`, which Grand Theft Auto VI creates +/// `ID3D12Device8`, and `ID3D12Device11`, which the title creates /// its device as. Each level's table is the one before plus its methods. const LEVEL_IIDS: [Iid; 9] = [ guid( @@ -94,7 +94,7 @@ pub(crate) fn is_device(iid: *const Iid) -> bool { } /// The interface version these layouts were checked against (2.4). Both -/// Minecraft (March 2022) and Grand Theft Auto VI (April 2026) pass it. +/// Minecraft (March 2022) and the title (April 2026) pass it. pub const CHECKED_VERSION: u32 = 0x0002_0004; /// Feature level 12_2, what the console hardware supports. @@ -160,7 +160,7 @@ pub extern "system" fn create( /// queues then have the newer layouts (two more methods each; see /// `list` and `queue`), although the interface version stays 2.4. /// shortcut: the creation interface is the only sign of the newer layouts -/// we have (Grand Theft Auto VI, April 2026, versus Minecraft, March 2022); +/// we have (the title, April 2026, versus Minecraft, March 2022); /// look for a better one if a title breaks the rule. static NEWER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -346,6 +346,59 @@ fn feature_levels(data: *mut c_void) -> HRESULT { } } +/// Device methods 0x1c8 and 0x218 (`SLOT`). The title calls both +/// (title+0x2477578 and title+0x24800d5) as `(this, description, interface +/// id, out)`, asks for `ID3D12PipelineState`, and on success keeps the +/// object `out` names and draws with it; on failure it goes without that +/// pipeline, silently. What the descriptions hold is not known: the calls +/// fail as they always did, with `out` null, and the first ones log the +/// description's words and what its first word points at, so that the two +/// methods can be written. +/// shortcut: not implemented. Answering `S_OK` here without making the +/// pipeline would hand the title whatever its stack held as an object. +extern "system" fn unknown_pipeline( + _: This, + desc: *const u8, + _iid: *const Iid, + out: *mut This, +) -> HRESULT { + use std::sync::atomic::{AtomicU32, Ordering}; + static CALLS: [AtomicU32; 2] = [const { AtomicU32::new(0) }; 2]; + let calls = CALLS[usize::from(SLOT == 0x218)].fetch_add(1, Ordering::Relaxed) + 1; + if !out.is_null() { + // SAFETY: the title's out pointer (a local of its own). + unsafe { *out = std::ptr::null() }; + } + if calls <= 4 || calls.is_power_of_two() { + // Sixteen 64-bit words at `at`, read through the kernel: neither + // pointer is known to be mapped. + #[cfg(windows)] + let words = |at: usize| -> Option> { + let mut bytes = [0u8; 128]; + (at != 0 && crate::host::read_into(at as *const u8, &mut bytes)).then(|| { + bytes + .as_chunks::<8>().0.iter() + .map(|c| c.iter().rev().fold(0u64, |v, &b| v << 8 | u64::from(b))) + .collect() + }) + }; + #[cfg(not(windows))] + let words = |_: usize| None::>; + let description = words(desc as usize); + let first = description + .as_ref() + .and_then(|w| words(w[0] as usize)); + tracing::warn!( + slot = format_args!("{:#x}", SLOT), + calls, + description = format_args!("{description:x?}"), + first_points_at = format_args!("{first:x?}"), + "a pipeline creation method that is not implemented: the title goes without this pipeline" + ); + } + E_NOTIMPL +} + /// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the /// methods `ID3D12Device1` to `ID3D12Device8` add, in order: 3, 1, 3, 6, 9, /// 1, 2, 9 (0x298-0x3a0, the console's own among them), then those of @@ -382,8 +435,10 @@ static FUNCTIONS: Table<160> = { f[39] = query::create as *const (); // 0x138 f[41] = signature::create as *const (); // 0x148 f[48] = queue::create_x as *const (); // 0x180 + f[57] = unknown_pipeline::<0x1c8> as *const (); // 0x1c8 f[61] = descriptor::create_sampler_x as *const (); // 0x1e8 f[62] = pipeline::create_compute_x as *const (); // 0x1f0 + f[67] = unknown_pipeline::<0x218> as *const (); // 0x218 f[69] = object::ignore as *const (); // 0x228 debug error filter f[70] = descriptor::create_placed_srv as *const (); // 0x230 f[71] = descriptor::create_placed_uav as *const (); // 0x238 @@ -435,7 +490,7 @@ mod tests { #[test] fn newer_device_levels_are_the_same_device() { - // ID3D12Device11, as Grand Theft Auto VI asks for it. + // ID3D12Device11, as the title asks for it. let (hr, device) = create_as(&LEVEL_IIDS[8]); assert_eq!((hr, device), (S_OK, super::device())); let mut same = std::ptr::null(); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d9e8f6a..54cd7fa 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -10,20 +10,19 @@ use std::sync::atomic::{AtomicU64, Ordering}; +use victory_shader::resource::RootIndexedView; use victory_shader::{ResourceType, RootType, UsedResource}; use crate::descriptor::View; use windows::Win32::Foundation::RECT; -use windows::Win32::Graphics::Direct3D::{ - D3D_PRIMITIVE_TOPOLOGY, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, -}; +use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; use windows::core::Interface; -use crate::host::{HostList, transition}; +use crate::host::HostList; use crate::object::This; -use crate::pipeline::host::{HostPipeline, Stage}; +use crate::pipeline::host::HostPipeline; /// A root argument as the title set it. #[derive(Debug, Clone, Default)] @@ -53,11 +52,136 @@ pub(crate) struct IndexView { format: u32, } -/// The root data sent to the host for one stage of the current draw. -#[cfg(feature = "diagnostics")] -struct BoundUserData { - values: Vec, - rebuilt_tables: Vec<(u8, u32)>, +/// Host states of a depth target, and of a texture shaders read. +const DEPTH_WRITE: u32 = 0x10; +const DEPTH_READ: u32 = 0x20; +const SHADER_RESOURCE: u32 = 0x40 | 0x80; + +thread_local! { + /// While a draw is prepared (`State::bind`, then its targets' states): + /// the depth target the draw only tests (0: none, or one it writes), + /// and whether a view its shaders read is of that same texture. + static TESTED_DEPTH: std::cell::Cell<(usize, bool)> = + const { std::cell::Cell::new((0, false)) }; + /// While a stage's tables are walked (`State::tables`): whether that + /// stage's shader can store to buffers (`Translated::stores`). + static STORES: std::cell::Cell = const { std::cell::Cell::new(true) }; + /// While `State::early_textures` runs the texture pass: the + /// milliseconds and the bytes that run may take, in place of the + /// pass's own per frame. + static PASS_BUDGET: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// The milliseconds of every frame the pass that uploads textures picked +/// by index takes before a shader that picks by index has asked for it +/// (`VICTORY_EARLY_TEXTURES_MS`, 12; 0: never, as before), and the +/// milliseconds it may take just before a draw of the title's decoration +/// bake (`VICTORY_BAKE_TEXTURES_MS`, 1500; 0: nothing special). +/// +/// The pass ran only from the first world frame on, where it met some +/// 24,000 slots at once and needed 60-80 frames for them. The title bakes +/// its characters' skin and decorations into textures of its own while it +/// loads, 159-1,165 frames before that (runs 156-174), with a pixel shader +/// that picks its sources by index: whatever was not on the card then was +/// baked as nothing, once, for the run. On the console a texture is there +/// when its bytes are. +fn early_budgets() -> (u64, u64) { + static MS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); + *MS.get_or_init(|| { + let ms = |name: &str, default: u64| { + std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(default) + }; + (ms("VICTORY_EARLY_TEXTURES_MS", 12), ms("VICTORY_BAKE_TEXTURES_MS", 1500)) + }) +} + +/// The pixel shaders of the title's decoration bake (the title: +/// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the +/// frame listings print it. They draw into a 256x256 corner of 2048x2048 +/// targets and name no texture in a table. +const BAKE_PIXEL_SHADERS: [&str; 4] = + ["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"]; + +/// Since the start: early runs of the texture pass, and those of them +/// made for a bake draw. +pub(crate) static EARLY_TEXTURE_PASSES: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + +/// Whether a buffer range a shader names through an unordered access view +/// is given to shaders as written (snapshot before the submission, compare +/// and write back after) only if that shader's code can store to buffers. +/// The title binds buffers its shaders only read through such views, and +/// every range declared costs a snapshot and a compare of its bytes: 3.97 +/// GB a frame in 31 submissions, 0.49 s of snapshots and 0.28 s of +/// comparing (run 28). On by default; `VICTORY_WRITE_SKIP=0` declares +/// every such range, as before. +fn write_skip() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WRITE_SKIP").is_none_or(|v| v != "0")) +} + +/// A run of indirect records clamped in one pass (`windows()`): the host +/// copy they came from (its number), their kind and stride, the offset of +/// the first in that copy, how many, and the list's scratch buffer that +/// holds them clamped, record `i` at `i * step`. +#[derive(Clone)] +struct Window { + copy: u64, + kind: u32, + stride: u32, + /// How far apart the records are in the copy, and in the scratch + /// buffer: what the title walks them by (`windows()`). + step: u32, + base: u64, + records: u32, + scratch: ID3D12Resource, +} + +/// The most records clamped in one pass (`windows()`). +const WINDOW_MOST: u64 = 64; + +/// Whether indirect draws that read record after record of one argument +/// buffer are clamped a window at a time (`VICTORY_INDIRECT_WINDOW=1`; off +/// by default). +/// +/// The title issues its mesh draws one record per call, each from the next +/// slot of the same argument buffer: 3,460 a frame in gameplay, and before +/// each our clamp ran as a compute dispatch of its own between two waits, +/// so the card went from drawing to compute and back for every record. In +/// the timing run of the lit scene (run 79) a shadow draw of next to +/// nothing cost 14-16 microseconds, 4,126 records a frame. +/// +/// With the switch, when a draw asks for a record a short step after the +/// one drawn before, the clamp takes that record and the ones that step +/// apart after it (16, then twice as many each time, [`WINDOW_MOST`] at +/// most, never past the buffer) into +/// the list's scratch buffer in one pass, and the draws that follow read +/// their record there with no pass of ours, until one of these: a compute +/// dispatch, a direct draw, an indirect call with a count buffer or more +/// than one record, a draw whose shaders can store to buffers, a record +/// outside the window, another host list. +/// +/// The step is the one the title is seen to take, not the stride its +/// command signature names: it draws one record a call, for which the +/// stride means nothing, and the title names 12 bytes (the three +/// words of a mesh dispatch) for records it keeps 32 bytes apart (2,173 of +/// a frame's 3,349 mesh records in run 87's listed frame; 283 are 16 +/// apart, which ends a window). Walked by the named stride the window +/// never opened: run 87, with the switch, still clamped 5,068 records a +/// frame one at a time. +/// +/// What it costs the guard against garbage records: nothing against a +/// hang (every record is bounded as before and charged to the list's +/// budget as before), but the budget is charged when a window is clamped, +/// so also for records of the window's tail that are never drawn. Those +/// hold garbage in this title (slots of all ones: run 93 spent lists' +/// budgets on them and emptied the draws after), so in a window a record +/// that asks for more than can run is left empty and charges nothing +/// (`crate::indirect::bound_ahead`); a tail record that looks real is +/// charged what it asks, a few thousand of 2^27. And arguments the title's CPU side changes are seen as +/// before, at the next submission. +fn windows() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1")) } /// What one title list has set, and what its host list was last given. @@ -73,42 +197,134 @@ pub(crate) struct State { /// Bound render target and depth resources, for their host states. targets: Vec, depth: usize, + /// The host state the bound depth view needs ([`depth_state`]). + depth_state: u32, /// The title's primitive topology (the host's may differ). topology: u32, + /// What the title set that goes straight onto the host list, kept for + /// the host list that continues this one after a cut ([`State::replay`]): + /// whether a topology was set, the render target and depth handles, the + /// viewports, the scissors, the blend factor and the stencil reference. + topology_set: bool, + target_handles: Vec, + depth_handle: u64, + targets_set: bool, + viewports: Vec, + scissors: Vec, + blend: Option<[f32; 4]>, + stencil: Option, + depth_bounds: Option<[f32; 2]>, + /// The indirect records clamped last, if later draws may still read + /// them (`windows()`). + window: Option, /// What the host list has: pipeline, root signature, heaps. host_pipeline: usize, /// Graphics, compute. host_roots: [usize; 2], host_heaps: [usize; 2], - /// Tables made afresh in this list: (table, what it holds) → first + /// Tables made afresh in this list: (table, slot count, contents) → first /// dynamic slot. - fresh_tables: std::collections::HashMap<(u64, u64), u32>, - /// Dynamic slots held by the recording, plus their cache keys so a - /// rejected bind can give back only the tables it reserved. - dynamic: Vec, - /// Root SRV views made in this list: (title heap, title address) → - /// dynamic slot (see [`State::bind_root_srv`]). - root_srv_slots: std::collections::HashMap<(usize, u64), u32>, - /// Address maps made in this list: title view heap, host GPU address. - maps: Vec<(usize, u64)>, - /// The values sent to each stage for the next device-removed marker. - #[cfg(feature = "diagnostics")] - bound_user_data: Vec, + fresh_tables: std::collections::HashMap<(u64, u32, u64), u32>, + /// The dynamic slots the list holds: title heap, first, count; given + /// back when the list has run, is reset or released. + dynamic: Vec<(usize, u32, u32)>, + /// Root SRVs bound as one-view tables in this list: (title heap, title + /// address; 0 for none) → dynamic slot, and the host copy the slot + /// shows: later draws of the list bring that one up to date, whatever + /// copy the address would find by then (`shadow.rs` `tails`). + root_srv_slots: std::collections::HashMap<(usize, u64), RootSlot>, + /// Root UAVs bound as one-view tables in this list, likewise. + root_uav_slots: std::collections::HashMap<(usize, u64), RootSlot>, + /// The list ran and its dynamic slots were given back. + tables_gone: bool, } -struct FreshTable { - key: (u64, u64), - heap: usize, - first: u32, - count: u32, +impl Drop for State { + fn drop(&mut self) { + for &(heap, first, n) in &self.dynamic { + crate::descriptor::release_dynamic(heap, first, n); + } + } } -impl Drop for FreshTable { - fn drop(&mut self) { - crate::descriptor::release_dynamic(self.heap, self.first, self.count); +impl State { + /// The list's submission has run (submissions are waited for): the + /// dynamic slots its tables were made in are given back, not kept + /// until the title resets the list. A frame of the opening cutscene + /// asks for 12,500 tables; held until the resets they ran the 131,072 + /// slots out, and up to 4,900 draws a frame went without their tables. + /// shortcut: a list the title runs a second time without a reset then + /// reads slots others may have taken (logged once). + pub(crate) fn tables_done(&mut self) { + if self.tables_gone && self.dynamic.is_empty() { + return; + } + if self.tables_gone { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("a list ran again after its descriptor tables were given back")); + } + for (heap, first, n) in self.dynamic.drain(..) { + crate::descriptor::release_dynamic(heap, first, n); + } + self.fresh_tables.clear(); + self.root_srv_slots.clear(); + self.root_uav_slots.clear(); + self.tables_gone = true; } } +/// An experiment on the title's scissor rectangles (`VICTORY_SCISSOR_TEST=full`): +/// they are all widened to the whole target. The title's room at +/// the start of the prologue lost its walls in five runs of seven, and in +/// those runs the player's body and the world outside were cut by one +/// rectangle around the window (run 85, frame 2046): one run with this on +/// says whether the walls are drawn and cut away by such a rectangle, or +/// not drawn at all. Off by default: a rectangle the title sets is part of +/// its picture. +fn scissor_test() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_SCISSOR_TEST").as_deref() == Ok("full")) +} + +/// An experiment on mesh draws (`VICTORY_MESH_TEST`): 1 for `skip` (none +/// is issued), 2 for `scissor` (each runs its shaders but rasterises one +/// pixel), 0 otherwise. It tells a card hung by a mesh shader from one hung +/// by what the shader's triangles cover. +fn mesh_test() -> u8 { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var("VICTORY_MESH_TEST").as_deref() { + Ok("skip") => 1, + Ok("scissor") => 2, + _ => 0, + }) +} + +/// `VICTORY_MESH_TEST=keep:[:]`: only the mesh +/// draws whose mesh shader's hash ends in one of the first digits (and +/// whose digit before it is one of the second, if given) are issued: a +/// search for the shaders that stop the card. +fn mesh_kept(pipeline: usize) -> bool { + static KEEP: std::sync::OnceLock> = std::sync::OnceLock::new(); + let Some((last, before)) = KEEP.get_or_init(|| { + let value = std::env::var("VICTORY_MESH_TEST").ok()?; + let mut parts = value.strip_prefix("keep:")?.split(':'); + Some((parts.next()?.to_owned(), parts.next().unwrap_or("").to_owned())) + }) else { + return true; + }; + let Some(p) = crate::pipeline::host_pipeline(pipeline as This) else { + return true; + }; + let Some(at) = p.name.find("mesh ") else { + return true; + }; + let hash = p.name[at + 5..].as_bytes(); + if hash.len() < 16 { + return true; + } + last.as_bytes().contains(&hash[15]) && (before.is_empty() || before.as_bytes().contains(&hash[14])) +} + /// Draws recorded on the host GPU since the last frame line. static DRAWN: AtomicU64 = AtomicU64::new(0); @@ -133,6 +349,71 @@ pub(crate) fn take_frame() -> Vec { pub(crate) fn take_dropped() -> u64 { DROPPED.swap(0, Ordering::Relaxed) } +/// A root SRV's dynamic slot in a list, and the host copy it shows. +type RootSlot = (u32, Option>); + +/// Buffer views of the heap whose slot showed another host buffer than +/// the copy the pass brought up to date for them, since the start +/// (diagnostics; for the memory line). It stays 0 while the pass and the +/// slots agree; with `VICTORY_VIEW_EXTENT=0` it counts the views that were +/// read stale. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0); +/// Passes over the view heap's buffer views for shaders that pick them by +/// index ([`State::heap_buffers`]), and the microseconds they took. +pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0); +pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0); +/// Textures brought up to date for shaders that pick them by index +/// ([`State::heap_textures`]), the bytes of their memory, and the slots +/// still waiting. +pub(crate) static HEAP_TEXTURES: AtomicU64 = AtomicU64::new(0); +pub(crate) static HEAP_TEXTURE_BYTES: AtomicU64 = AtomicU64::new(0); +pub(crate) static HEAP_TEXTURES_WAITING: AtomicU64 = AtomicU64::new(0); +/// Passes that made no texture because the card had no room +/// (`crate::resource::room`), for the memory line. +pub(crate) static HEAP_TEXTURES_FULL: AtomicU64 = AtomicU64::new(0); + +/// Frames after a whole upload of a texture picked by index at which its +/// memory is looked at again, each counted from the look before. +const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400]; + +/// Looks at uploaded textures picked by index that found the memory as it +/// was, and that found it changed (uploaded again), since the start. +pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + +/// Uploads of textures already on the card made while it had no room for +/// new ones, since the start. +pub(crate) static HEAP_TEXTURES_REUPLOADED_FULL: AtomicU64 = AtomicU64::new(0); + +/// Whether a texture that has its host copy is still brought up to date +/// while the card has no room for new ones (`VICTORY_REUPLOAD_WHEN_FULL=0`: +/// no). +fn reupload_when_full() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_REUPLOAD_WHEN_FULL").is_none_or(|v| v != "0")) +} + +/// Whether textures picked by index are looked at again after their upload +/// (`VICTORY_HEAP_RECHECK=0`: no). +fn heap_recheck() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_RECHECK").is_none_or(|v| v != "0")) +} +/// Times a placed texture's slot was passed over because its memory is not +/// mapped. +pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0); +/// Slots the pass found up to date already: their texture is uploaded by +/// the draws that read it through a table (it has a staging buffer). +pub(crate) static HEAP_TEXTURES_TABLED: AtomicU64 = AtomicU64::new(0); +/// The queue of textures picked by index at the last pass +/// (`TextureQueue::census`): slots in it, due, waiting for their memory, +/// uploaded in part, and the frames the oldest due one has waited. +pub(crate) static HEAP_TEXTURES_QUEUE: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; +/// Since the start: looks at a slot uploaded in part that found no more of +/// its memory mapped; uploads of textures not all mapped; and of those, +/// the ones whose first page was not there (asked by the first page alone, +/// as before, they counted as not there at all). +pub(crate) static HEAP_TEXTURES_PARTLY: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; static DROPPED: AtomicU64 = AtomicU64::new(0); /// Marks the last traced draw as not run on the host. @@ -154,16 +435,26 @@ pub(crate) fn dispatched() -> u64 { /// The host address of a root view: its buffer's host copy, or for a /// constant buffer not 256-byte aligned there (the console needs 16) a /// copy in upload memory. -/// shortcut: a root view has no size; constant buffers are taken as 64 KiB, -/// other views as 1 MiB (both cut at their buffer's end). +/// shortcut: a root view has no size; constant buffers are taken as 64 KiB +/// (cut at their buffer's end), other views as all that is left of their +/// buffer. (They were taken as 1 MiB: 1,452 of the 2,021 mesh vertex +/// streams of a cutscene frame reach further, and what lay past the first +/// megabyte was never brought up to date - meshes without bodies, exploded +/// triangles. `VICTORY_ROOT_VIEW_MB` sets a limit again.) fn root_view(list: &HostList, address: u64, srv: bool) -> Option { + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + std::env::var("VICTORY_ROOT_VIEW_MB") + .ok() + .and_then(|v| v.parse::().ok()) + .map_or(u64::MAX, |mb| mb << 20) + }); let shadow = crate::shadow::find(address, 1)?; let len = shadow .left(address) - .min(if srv { 1 << 20 } else { 1 << 16 }); + .min(if srv { limit } else { 1 << 16 }); let gpu = shadow.gpu(address); if srv || gpu % 256 == 0 { - crate::list::ensure_shadow_state(list, &shadow, if srv { 0x40 | 0x80 } else { 0x1 }); shadow.refresh(list, address, len); return Some(gpu); } @@ -197,6 +488,7 @@ impl State { /// [`crate::primitive`]). pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) { self.topology = topology; + self.topology_set = true; let host = match topology { RECTANGLES => 4, TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => { @@ -266,12 +558,7 @@ impl State { } pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) { - for slot in self - .vertex - .iter_mut() - .skip(start as usize) - .take(count as usize) - { + for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) { *slot = VertexView::default(); } } @@ -285,6 +572,10 @@ impl State { let Some(host) = crate::host::host() else { return; }; + self.target_handles.clear(); + self.target_handles.extend_from_slice(handles); + self.depth_handle = depth; + self.targets_set = true; self.targets.clear(); let mut rtvs = Vec::new(); for &h in handles { @@ -296,20 +587,34 @@ impl State { continue; }; let Some(texture) = crate::resource::host_resource(record.resource) else { - continue; - }; - let Some(rtv) = host.rtv(texture, record.desc().as_ref()) else { + // A typed null view (or a target without a host copy) still + // takes its slot: left out, the next live target would move + // into it and the pixel shader's outputs reach the wrong + // targets. + // shortcut: a view without a description or a format has no + // null view to stand for it and is left out, as before. + let null = record + .desc() + .filter(|d| d.Format.0 != 0 && d.ViewDimension.0 != 0); + if let Some(desc) = null { + rtvs.push(host.rtv(None, Some(&desc))); + } continue; }; self.targets.push(record.resource as usize); #[cfg(feature = "diagnostics")] crate::capture::note_target(record.resource); - rtvs.push(rtv); + rtvs.push(host.rtv(Some(texture), record.desc().as_ref())); } self.depth = 0; + self.depth_state = DEPTH_WRITE; let dsv = crate::descriptor::dsv_record(depth).and_then(|record| { let texture = crate::resource::host_resource(record.resource)?; self.depth = record.resource as usize; + self.depth_state = depth_state(texture, record.depth_desc().as_ref()); + if crate::resource::depth_and_unordered(record.resource) { + crate::resource::DEPTH_UNORDERED[1].fetch_add(1, Ordering::Relaxed); + } #[cfg(feature = "diagnostics")] crate::capture::note_target(record.resource); Some(host.dsv(texture, record.depth_desc().as_ref())) @@ -325,15 +630,87 @@ impl State { }; } - /// The bound view heap's breadcrumb entry, which shaders store loop - /// counts through (see [`crate::breadcrumb`]). - fn breadcrumb_slot(&self) -> u32 { - let heap = self.heaps[0]; - (heap != 0) - .then(|| crate::descriptor::heap(heap as This).host()) - .flatten() - .and_then(|h| h.breadcrumb_slot()) - .unwrap_or(0) + /// Viewports, scissors, the blend factor and the stencil reference: set + /// on the host list at once, and kept for [`State::replay`]. + pub(crate) fn set_viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) { + self.viewports.clear(); + self.viewports.extend_from_slice(viewports); + crate::draw::viewports(list, viewports); + } + + pub(crate) fn set_scissors(&mut self, list: &HostList, rects: &[RECT]) { + self.scissors.clear(); + self.scissors.extend_from_slice(rects); + if scissor_test() { + // The experiment: every rectangle the title sets is widened to + // the largest target there is, so nothing is cut by one. What + // the listing shows (`op_text`) stays the title's own. + let full = RECT { + left: 0, + top: 0, + right: 16384, + bottom: 16384, + }; + crate::draw::scissors(list, &vec![full; rects.len()]); + return; + } + crate::draw::scissors(list, rects); + } + + pub(crate) fn set_blend_factor(&mut self, list: &HostList, factor: Option<&[f32; 4]>) { + self.blend = factor.copied(); + crate::draw::blend_factor(list, factor); + } + + pub(crate) fn set_stencil_ref(&mut self, list: &HostList, reference: u32) { + self.stencil = Some(reference); + crate::draw::stencil_ref(list, reference); + } + + pub(crate) fn set_depth_bounds(&mut self, list: &HostList, min: f32, max: f32) { + self.depth_bounds = Some([min, max]); + crate::draw::depth_bounds(list, min, max); + } + + /// `list` is a new host list that continues the title's list (it was + /// cut at a wait for a memory value, `crate::list::cut`): a new host + /// list has nothing set, so what the title set so far is set again. + /// The pipeline, the root signatures and the heaps are set by the next + /// draw or dispatch (`bind`, which is told here that the host list has + /// none); root arguments, vertex and index buffers are set by every + /// draw anyway. The dynamic descriptor slots and the tables made in + /// them stay: the parts before the cut have not run yet, and they are + /// given back when the title's list is reset. + /// shortcut: the render target views are made again from the handles' + /// descriptors as they are now, not as they were when the title set + /// the targets (a descriptor rewritten in between names another view). + pub(crate) fn replay(&mut self, list: &HostList) { + self.host_pipeline = 0; + self.host_roots = [0; 2]; + self.host_heaps = [0; 2]; + if self.topology_set { + self.set_topology(list, self.topology); + } + if self.targets_set { + let handles = std::mem::take(&mut self.target_handles); + self.set_targets(list, &handles, self.depth_handle); + } + if !self.viewports.is_empty() { + crate::draw::viewports(list, &self.viewports); + } + if !self.scissors.is_empty() { + let rects = std::mem::take(&mut self.scissors); + self.set_scissors(list, &rects); + } + if let Some(factor) = self.blend { + crate::draw::blend_factor(list, Some(&factor)); + } + if let Some(reference) = self.stencil { + crate::draw::stencil_ref(list, reference); + } + if let Some([min, max]) = self.depth_bounds { + crate::draw::depth_bounds(list, min, max); + } } /// The user-data value of a root argument, as translated shaders read @@ -353,6 +730,8 @@ impl State { (Some(Root::Constants(c)), RootType::Constants) => { c.get(dword as usize).copied().unwrap_or(0) } + // The host's own ([`Self::host_word`]): no root argument. + (_, RootType::Other(_)) => 0, _ => { once!( slot, @@ -364,6 +743,73 @@ impl State { } } + /// A user-data dword the host computes for a translated shader + /// (`victory_shader::emit::USER_MEMORY_BASE`, `USER_VIEW_ADDRESS`). + fn host_word( + &self, + compute: bool, + kind: u32, + slot: u8, + dword: u32, + memory: Option<&crate::memory::Ready>, + ) -> u32 { + use victory_shader::emit::{USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS}; + if kind == USER_MEMORY_BASE { + return memory.map_or(0, |m| m.base); + } + if kind == USER_VIEW_BIAS { + // The view begins on 16 bytes of the copy the address finds + // (`root_uav`, `root_srv_table`). + // shortcut: found again here, not taken from the list's slot. + return match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::View(address)) => crate::shadow::find(address, 1).map_or(0, |s| { + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + ((s.gpu(address) - base) & 15) as u32 + }), + _ => 0, + }; + } + if kind != USER_VIEW_ADDRESS && kind != USER_VIEW_ADDRESS + 1 { + once!(kind, "a shader reads a host value this build does not know"); + return 0; + } + // The title address of the buffer view at that dword of the table. + let address = match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4) + .and_then(|view| crate::descriptor::host::buffer_range(&view)) + .map_or(0, |range| range.0), + _ => 0, + }; + if address == 0 { + once!(slot, dword, "a shader takes the address of a buffer view that is not there: it reads 0"); + } + if kind == USER_VIEW_ADDRESS { + address as u32 + } else { + (address >> 32) as u32 + } + } + + /// For a shader that reads title memory by address + /// ([`crate::memory`]): its directory, fault notes and view slots, + /// with the pages of the root views the list has set made ready. + fn memory_ready(&self, list: &HostList, compute: bool, writes: bool) -> Option { + let heap = match self.heaps[0] { + 0 => None, + h => crate::descriptor::heap(h as This).host(), + }?; + let (mut addresses, mut constants) = (Vec::new(), Vec::new()); + for root in self.roots_ref(compute) { + match root { + Root::View(address) => addresses.push(*address), + Root::Constants(values) => constants.extend_from_slice(values), + _ => {} + } + } + crate::memory::ready(list, heap, &addresses, &constants, writes) + } + /// The bound heap holding `handle`. fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> { self.heaps @@ -389,12 +835,13 @@ impl State { return false; }; if p.compute || p.mesh != mesh { - once!( - mesh, - "a draw or mesh dispatch with another kind of pipeline" - ); + once!(mesh, "a draw or mesh dispatch with another kind of pipeline"); return false; } + if p.rects && self.topology != RECTANGLES { + // Its geometry stage would turn each triangle into a rectangle. + once!("a rectangle pipeline drawn with another topology"); + } if !self.bind(list, p, false) { return false; } @@ -410,10 +857,9 @@ impl State { if v.address == 0 || v.size == 0 { continue; } - let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { + let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { continue; }; - crate::list::ensure_shadow_state(list, &shadow, 0x1); shadow.refresh(list, v.address, u64::from(v.size)); *view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: shadow.gpu(v.address), @@ -429,10 +875,9 @@ impl State { } if indexed { let v = self.index; - let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { + let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { return false; }; - crate::list::ensure_shadow_state(list, &shadow, 0x2); shadow.refresh(list, v.address, u64::from(v.size)); let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: shadow.gpu(v.address), @@ -442,19 +887,31 @@ impl State { // SAFETY: an open list; the view names a live host buffer. unsafe { l.IASetIndexBuffer(Some(&view)) }; } - self.ensure_targets(list); - true - } - - fn ensure_targets(&self, list: &HostList) { const RENDER_TARGET: u32 = 0x4; - const DEPTH_WRITE: u32 = 0x10; for &t in &self.targets { crate::list::ensure_state(list, t as This, RENDER_TARGET); } if self.depth != 0 { - crate::list::ensure_state(list, self.depth as This, DEPTH_WRITE); + // A depth texture shaders also write: what they wrote, first. + list.twin_use(self.depth as This, false, true); + // A view that writes neither plane keeps the texture readable: + // the depth read state, together with the shader read states + // if this draw's shaders read the same texture (the write state + // put it out of the state those views need, and a move to it + // and back for every such draw). + let state = if self.depth_state == DEPTH_READ { + let (tested, read) = TESTED_DEPTH.get(); + if read && tested == self.depth { + DEPTH_READ | SHADER_RESOURCE + } else { + DEPTH_READ + } + } else { + DEPTH_WRITE + }; + crate::list::ensure_state(list, self.depth as This, state); } + true } /// A descriptor a shader reads through a table: its host slot made if @@ -462,32 +919,14 @@ impl State { /// What draws and dispatches share: heaps, our root signature, the /// pipeline, and per stage the user data, root views and the /// descriptors its tables hold. - /// 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 { - self.bind_parts(list, &p.root, &p.pso, &p.name, &p.stages, compute, compute) - } - - /// [`State::bind`], split so mesh emulation can bind its compute step - /// against the title's graphics root arguments while writing host - /// compute root parameters. - #[allow(clippy::too_many_arguments)] - fn bind_parts( - &mut self, - list: &HostList, - root_signature: &ID3D12RootSignature, - pso: &ID3D12PipelineState, - name: &str, - stages: &[Stage], - title_compute: bool, - host_compute: bool, - ) -> bool { + /// False if the draw or dispatch must not run: a root SRV it reads + /// could not be given a view. + pub(crate) fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { let l = &list.list; - #[cfg(feature = "diagnostics")] - let record_bindings = crate::host::dred_on(); - #[cfg(feature = "diagnostics")] - if record_bindings { - self.bound_user_data.clear(); + // Textures picked by index, before anything asks for them. + self.early_textures(list, p, compute); + if crate::host::walls_trace() { + self.walls_census(p, compute); } // Heaps first: a root signature with directly indexed heaps must be // set after them. @@ -505,144 +944,156 @@ impl State { self.host_heaps = self.heaps; self.host_roots = [0; 2]; } - let root = root_signature.as_raw() as usize; - if self.host_roots[usize::from(host_compute)] != root { + // The depth target a draw only tests, for the views of it that the + // draw's shaders read (`readable`). + let tested = if !compute && self.depth_state == DEPTH_READ { + self.depth + } else { + 0 + }; + TESTED_DEPTH.set((tested, false)); + let root = p.root.as_raw() as usize; + if self.host_roots[usize::from(compute)] != root { // SAFETY: an open list and a live root signature. unsafe { - if host_compute { - l.SetComputeRootSignature(root_signature); + if compute { + l.SetComputeRootSignature(&p.root); } else { - l.SetGraphicsRootSignature(root_signature); + l.SetGraphicsRootSignature(&p.root); } } - self.host_roots[usize::from(host_compute)] = root; + self.host_roots[usize::from(compute)] = root; } // By host object: a title pipeline released and another made at its // address is another host pipeline (the list keeps the old one). - if self.host_pipeline != pso.as_raw() as usize { + if self.host_pipeline != p.pso.as_raw() as usize { // SAFETY: an open list and a live pipeline. - unsafe { l.SetPipelineState(pso) }; - self.host_pipeline = pso.as_raw() as usize; - list.used_pipeline(name); + unsafe { l.SetPipelineState(&p.pso) }; + self.host_pipeline = p.pso.as_raw() as usize; + list.used_pipeline(&p.name); // The title may release the pipeline before it submits the list. - list.keep(pso); - list.keep(root_signature); + list.keep(&p.pso); + list.keep(&p.root); } - let reserved_before_bind = self.dynamic.len(); - for stage in stages { + for stage in &p.stages { let t = stage.translated(); - let Some(made) = self.tables(list, &t.used, title_compute) else { - self.release_rejected_tables(reserved_before_bind); - static DROPPED_TABLES: AtomicU64 = AtomicU64::new(0); - let n = DROPPED_TABLES.fetch_add(1, Ordering::Relaxed) + 1; - if n.is_power_of_two() { - tracing::warn!( - dropped = n, - "a draw or dispatch dropped: no dynamic slots for its tables" - ); - } + STORES.set(t.stores); + let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute); + STORES.set(true); + if made.iter().any(|m| m.1 == u32::MAX) { + once!("a draw whose descriptor table found no free slots is dropped"); return false; + } + // What the shader stores through root views and raw addresses is + // copied back into title memory afterwards. + let writes = (t.stores || !write_skip()) + && !crate::pipeline::builder_quarantined(self.pipeline as This); + // Title memory by address: what the shader finds it by. + let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) { + let Some(ready) = self.memory_ready(list, compute, writes) else { + once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped"); + return false; + }; + Some(ready) + } else { + None }; - let mut values = Vec::new(); if let Some((param, dwords)) = stage.user_data { - values.resize(dwords as usize, 0); + let mut values = vec![0u32; dwords as usize]; for u in &t.host.user_data { + if let RootType::Other(kind) = u.root { + values[u.index as usize] = + self.host_word(compute, kind, u.slot, u.dword, memory.as_ref()); + continue; + } let fresh = made .iter() .find(|m| m.0 == u.slot && u.root == RootType::Table); values[u.index as usize] = match fresh { Some(&(_, offset)) => offset, - None if u.root == victory_shader::emit::BREADCRUMB_ROOT => { - self.breadcrumb_slot() - } - None => self.user_value(title_compute, u.slot, u.root, u.dword), + None => self.user_value(compute, u.slot, u.root, u.dword), }; } // SAFETY: an open list; `values` covers the parameter. unsafe { - if host_compute { + if compute { l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); } else { l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); } } } - // The address map and the descriptor words belong to the view - // heap: without them the shader would read nothing it expects. - let heap = (self.heaps[0] != 0) - .then(|| crate::descriptor::heap(self.heaps[0] as This).host()) - .flatten(); - let mut extra = Vec::new(); - if let Some(param) = stage.address_map { - let made = self.maps.iter().find(|m| m.0 == self.heaps[0]).map(|m| m.1); - let gpu = match (made, heap) { - (Some(gpu), _) => Some(gpu), - (None, Some(h)) => { - crate::address_map::make(list, h).map(|(gpu, (first, n))| { - if n > 0 { - self.dynamic.push(FreshTable { - key: (0, 0), - heap: self.heaps[0], - first, - count: n, - }); - } - self.maps.push((self.heaps[0], gpu)); - gpu - }) - } - (None, None) => None, - }; - let Some(gpu) = gpu else { - once!("a draw or dispatch dropped: no address map for its view heap"); - return false; - }; - extra.push((param, gpu)); - } - if let Some(param) = stage.descriptor_words { - let Some(gpu) = heap.and_then(|h| h.words()) else { - once!("a draw or dispatch dropped: no descriptor words for its view heap"); - return false; - }; - extra.push((param, gpu)); - } - for (param, gpu) in extra { - // SAFETY: an open list; the buffers live as long as it runs. - unsafe { - if host_compute { - l.SetComputeRootShaderResourceView(param, gpu); - } else { - l.SetGraphicsRootShaderResourceView(param, gpu); - } - } - } - #[cfg(feature = "diagnostics")] - if record_bindings { - self.bound_user_data.push(BoundUserData { - values, - rebuilt_tables: made, - }); - } for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { for &(slot, param) in views { - // Root SRVs are bounded one-view tables (see the host - // root signature). - if srv { - self.bind_root_srv(list, title_compute, host_compute, slot, param); + if srv && slot == victory_shader::emit::SLOT_MEMORY { + // Ours: the directory of title memory by address. + if let Some(m) = &memory { + // SAFETY: an open list; the directory lives as + // long as the process and the list holds it. + unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, m.directory); + } else { + l.SetGraphicsRootShaderResourceView(param, m.directory); + } + } + } continue; } - let Some(Root::View(address)) = - self.roots_ref(title_compute).get(usize::from(slot)) + if srv && slot == victory_shader::emit::SLOT_STRIDES { + // Ours, not the title's: the shader picks buffers + // from the view heap by an index it computes. + match self.heap_buffers(list) { + // SAFETY: an open list; the table lives as long + // as the heap the list holds. + Some(gpu) => unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); + } + }, + None => once!("a shader picks buffers from a view heap that is not set"), + } + continue; + } + let tabled = srv && crate::pipeline::host::bounded_root_srvs(); + 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"); + // A table left unset is undefined: a null view. + if tabled && !self.root_srv_table(list, None, param, compute, false) { + return false; + } continue; }; - let Some(gpu) = root_view(list, *address, srv) else { + // The shader adds the bytes a raw view begins early by. + let biased = srv + && t.host.user_data.iter().any(|u| { + u.slot == slot + && u.root == RootType::Other(victory_shader::emit::USER_VIEW_BIAS) + }); + if tabled { + if !self.root_srv_table(list, Some(address), param, compute, biased) { + return false; + } + continue; + } + let Some(mut gpu) = root_view(list, address, srv) else { continue; }; + if biased { + gpu -= u64::from(self.host_word( + compute, + victory_shader::emit::USER_VIEW_BIAS, + slot, + 0, + None, + )); + } // SAFETY: an open list; the address is in live memory. unsafe { - match (host_compute, srv) { + match (compute, srv) { (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu), (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu), (true, false) => l.SetComputeRootConstantBufferView(param, gpu), @@ -651,171 +1102,897 @@ impl State { } } } + for &(slot, param) in &stage.root_uavs { + if slot == victory_shader::emit::SLOT_FAULTS { + // Ours: where shaders note the pages they found empty. + if let Some(m) = &memory { + // SAFETY: an open list; the buffer lives as long as + // the process and the list holds it. + unsafe { + if compute { + l.SetComputeRootUnorderedAccessView(param, m.faults); + } else { + l.SetGraphicsRootUnorderedAccessView(param, m.faults); + } + } + } + continue; + } + let address = match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::View(address)) => Some(address), + _ => { + once!(slot, "a shader writes through a root view the title did not set"); + None + } + }; + if !self.root_uav(list, address, param, compute, writes) { + return false; + } + } } + // Depth textures it writes through unordered access: their colour + // twins hold what they lack from here on. + list.twins_written(); true } - /// Binds the title's root SRV `slot` as the one-view table `param` (see - /// the host root signature): a raw view of the rest of the title - /// buffer's host copy, in a dynamic slot of the bound view heap, so - /// reads past the copy return zeros rather than fault. Zeros (our null - /// buffer) if the title set none or it lies outside every buffer. - fn bind_root_srv( + /// Binds a root UAV: a raw unordered access view of the title buffer's + /// host copy from `address` on, as a one-view table (a null view + /// without an address, without a host copy shaders can write, or at an + /// address not on 16 bytes), or as a root descriptor with + /// `VICTORY_ROOT_SRV_DIRECT=1` (the dispatch is dropped then if there + /// is nothing to bind). With `writes`, what the shader stored is copied + /// back into title memory when the list has run. False if the draw + /// must be dropped. + /// shortcut: a root view has no size: the view, the refresh and the + /// copy back cover all that is left of the title's buffer + /// (`VICTORY_ROOT_UAV_MB` sets a limit for all three). + fn root_uav( &mut self, list: &HostList, - title_compute: bool, - host_compute: bool, - slot: u8, + address: Option, param: u32, - ) { - let l = &list.list; - let heap = self.heaps[0]; - if heap == 0 { - once!("a root SRV with no view heap bound: left unset"); - return; - } - let title_heap = crate::descriptor::heap(heap as This); - let Some(host) = title_heap.host() else { - return; + compute: bool, + writes: bool, + ) -> bool { + const UNORDERED: i32 = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0; + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + std::env::var("VICTORY_ROOT_UAV_MB") + .ok() + .and_then(|v| v.parse::().ok()) + .map_or(u64::MAX, |mb| mb << 20) + }); + let find = |a: u64| { + let s = crate::shadow::find(a, 1)?; + // SAFETY: a live buffer. + let flags = unsafe { s.buffer.GetDesc() }.Flags; + if flags.0 & UNORDERED == 0 { + once!("a root UAV of a buffer whose host copy shaders cannot write"); + return None; + } + Some(s) }; - let address = match self.roots_ref(title_compute).get(usize::from(slot)) { - Some(Root::View(address)) => *address, - _ => 0, + let ready = |a: u64, s: &std::sync::Arc| { + let len = s.left(a).min(limit); + s.refresh(list, a, len); + if writes { + s.gpu_writes(list, a, len); + } }; - let shadow = crate::shadow::find(address, 1) - .filter(|_| address != 0) - .map(|s| (s, address)); - // The same buffer again in this list: its slot, refreshed again. - if let Some(&index) = self.root_srv_slots.get(&(heap, address)) { - if let Some((shadow, address)) = &shadow { - shadow.refresh(list, *address, shadow.left(*address).min(1 << 20)); - } - let table = host.gpu_handle(index); - // SAFETY: an open list; the slot is held by this list. + if !crate::pipeline::host::bounded_root_srvs() { + let Some((a, s)) = address.and_then(|a| Some((a, find(a)?))) else { + once!("a root UAV with nothing to bind: the draw is dropped"); + return false; + }; + ready(a, &s); + // From the 16 bytes below: the shader adds the rest. + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + let gpu = base + ((s.gpu(a) - base) & !15); + // SAFETY: an open list; the address is in a live buffer. unsafe { - if host_compute { - l.SetComputeRootDescriptorTable(param, table); + if compute { + list.list.SetComputeRootUnorderedAccessView(param, gpu); } else { - l.SetGraphicsRootDescriptorTable(param, table); + list.list.SetGraphicsRootUnorderedAccessView(param, gpu); } } - return; + return true; } - let Some(index) = host.dynamic(1) else { - once!("no free dynamic slot for a root SRV: left unset"); - return; + let heap = match self.heaps[0] { + 0 => None, + h => Some(crate::descriptor::heap(h as This)), }; - self.dynamic.push(FreshTable { - key: (0, 0), - heap, - first: index, - count: 1, - }); - self.root_srv_slots.insert((heap, address), index); - match shadow { - Some((shadow, address)) => { - let len = shadow.left(address); - shadow.refresh(list, address, len.min(1 << 20)); - host.raw_srv_at(index, &shadow.buffer, shadow.offset(address), len); - } + let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else { + once!("a root UAV without a bound view heap: the draw is dropped"); + return false; + }; + let key = (std::ptr::from_ref(heap) as usize, address.unwrap_or(0)); + let (index, shadow) = match self.root_uav_slots.get(&key) { + Some((index, shadow)) => (*index, address.zip(shadow.clone())), None => { - once!( - slot, - "a root SRV the title did not set, or outside every buffer: reads zeros" - ); - host.make_null(index); + let shadow = address.and_then(|a| find(a).map(|s| (a, s))); + let Some(index) = host.dynamic(1) else { + return false; + }; + self.dynamic.push((key.0, index, 1)); + if let Some((a, s)) = &shadow { + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + let offset = s.gpu(*a) - base; + // Raw views start on 16 bytes: from the 16 bytes + // below, and the shader adds the rest to its offsets + // (`victory_shader::emit::USER_VIEW_BIAS`). (An address + // not on 16 bytes got a null view at first: the + // builder's counters are at such addresses.) + let bias = offset & 15; + host.raw_uav_at(index, &s.buffer, offset - bias, s.left(*a).min(limit) + bias); + } + if shadow.is_none() { + host.null_raw_uav_at(index); + } + self.root_uav_slots + .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone()))); + (index, shadow) } + }; + if let Some((a, s)) = &shadow { + ready(*a, s); } - let table = host.gpu_handle(index); - // SAFETY: an open list; the slot is in the bound heap and held by - // this list until it is reset. + let handle = host.gpu_handle(index); + // SAFETY: an open list; the slot is in the bound view heap. unsafe { - if host_compute { - l.SetComputeRootDescriptorTable(param, table); + if compute { + list.list.SetComputeRootDescriptorTable(param, handle); } else { - l.SetGraphicsRootDescriptorTable(param, table); + list.list.SetGraphicsRootDescriptorTable(param, handle); } } + true } - fn bind_emulated_cs( + /// Binds a root SRV as a one-view table + /// ([`crate::pipeline::host::bounded_root_srvs`]): a raw view of the + /// title buffer's host copy from `address` to the copy's end, or a null + /// view (no address, no host copy, or an address not on 16 bytes). One + /// dynamic slot per address per list, given back with the list's + /// others. False if no slot could be had or no view heap is bound. + fn root_srv_table( &mut self, list: &HostList, - p: &HostPipeline, - buffers: &crate::mesh_emu::Buffers, - base_group: u32, + address: Option, + param: u32, + compute: bool, + biased: bool, ) -> bool { - let Some(emu) = &p.mesh_emu else { - return false; + let heap = match self.heaps[0] { + 0 => None, + h => Some(crate::descriptor::heap(h as This)), }; - if !self.bind_parts( - list, - &emu.cs_root, - &emu.cs_pso, - &p.name, - std::slice::from_ref(&emu.cs_stage), - false, - true, - ) { + let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else { + once!("a root SRV without a bound view heap: the draw is dropped"); return false; - } - let l = &list.list; - // SAFETY: an open list; emulation buffers are static and also kept - // with the list below. - unsafe { - l.SetComputeRootUnorderedAccessView(emu.cs_uav_param, buffers.output_gpu); - if let Some(param) = emu.cs_cbv_param { - let constants = [base_group, 0, 0, 0]; - l.SetComputeRoot32BitConstants(param, 4, constants.as_ptr().cast(), 0); + }; + // A view that begins early is another view than one that does not + // (title addresses stay below bit 63). + let key = ( + std::ptr::from_ref(heap) as usize, + address.unwrap_or(0) | u64::from(biased) << 63, + ); + let (index, shadow) = match self.root_srv_slots.get(&key) { + Some((index, shadow)) => (*index, address.zip(shadow.clone())), + None => { + let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s))); + let Some(index) = host.dynamic(1) else { + return false; + }; + self.dynamic.push((key.0, index, 1)); + self.root_srv_slots + .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone()))); + match &shadow { + Some((a, s)) => { + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + let offset = s.gpu(*a) - base; + if biased { + // From the 16 bytes below; the shader adds the + // rest (`victory_shader::emit::USER_VIEW_BIAS`). + let bias = offset & 15; + host.raw_at(index, &s.buffer, offset - bias, s.left(*a) + bias); + } else if offset.is_multiple_of(16) { + host.raw_at(index, &s.buffer, offset, s.left(*a)); + } else { + // Raw views start on 16 bytes; one from the + // aligned start would shift every read. + once!( + address = format_args!("{a:#x}"), + "a root SRV not on 16 bytes reads zeros" + ); + host.null_raw_at(index); + } + } + None => host.null_raw_at(index), + } + (index, shadow) } - if let Some(param) = emu.cs_srv_param { - l.SetComputeRootShaderResourceView(param, buffers.dummy_srv_gpu); + }; + // As for root descriptors (`root_view`): all that is left of the + // buffer is brought up to date. The first 1 MiB only left what lay + // past it stale (most mesh vertex streams reach further). + if let Some((a, s)) = &shadow { + s.refresh(list, *a, s.left(*a)); + } + let handle = host.gpu_handle(index); + // SAFETY: an open list; the slot is in the bound view heap. + unsafe { + if compute { + list.list.SetComputeRootDescriptorTable(param, handle); + } else { + list.list.SetGraphicsRootDescriptorTable(param, handle); } } - list.keep(&buffers.output); - list.keep(&buffers.dummy_srv); true } - fn bind_emulated_gfx( - &mut self, - list: &HostList, - p: &HostPipeline, - buffers: &crate::mesh_emu::Buffers, - ) -> bool { - let Some(emu) = &p.mesh_emu else { - return false; + /// For a shader that picks buffers from the view heap by an index it + /// computes (SM 6.6 dynamic resources): the GPU address of the heap's + /// table of element strides, with every buffer view of the heap given + /// its host slot and its memory brought up to date when `list` is + /// submitted. Tables tell us which views a draw reads; nothing tells + /// us which of the heap's a computed index names, so all of them are + /// made ready, once per list. + /// shortcut: the buffers are read, not written: what such a shader + /// writes through a picked unordered access view stays in the host + /// copy. A list refreshes them where it first runs such a shader; + /// title writes recorded later in the same list are not seen. + fn heap_buffers(&self, list: &HostList) -> Option { + let heap = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers())?; + let host = heap.host()?; + let gpu = host.strides_gpu()?; + // One key per list, as textures have: no title resource is there. + const ONCE: usize = usize::MAX - 0x5e; + if !list.first_use(ONCE) { + return Some(gpu); + } + // The list may outlive the title's heap object, which owns the table. + if let Some(buffer) = host.strides_buffer() { + list.keep(buffer); + } + // The pass itself once per frame: per list it ran up to 51 times a + // frame over 81,000 views and 4,100 host copies, 18 s of every + // frame (2026-11-24, run 11). + // shortcut: what the title writes into such buffers between lists + // of one frame is seen a frame late. + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + let frame = crate::frame::current(); + if FRAME.swap(frame, Ordering::Relaxed) == frame { + return Some(gpu); + } + let started = std::time::Instant::now(); + // Per host heap: the host copy and range each slot's buffer view + // reads, kept from pass to pass. Only the slots written since the + // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s + // at best); all of them every 16 passes, because a view of a + // released resource goes stale without a write, and a slot written + // before its memory had a host copy is only made then. + type Ranges = std::collections::HashMap, u64, u64)>; + static RANGES: std::sync::Mutex>> = + std::sync::Mutex::new(None); + let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); + let (passes, ranges) = kept + .get_or_insert_with(Default::default) + .entry(std::ptr::from_ref(host) as usize) + .or_insert_with(|| (0, Ranges::new())); + let changed = host.buffer_changes(); + let slots = if *passes % 16 == 0 { + ranges.clear(); + host.buffer_slots() + } else { + changed }; - if !self.bind_parts(list, &p.root, &p.pso, &p.name, &p.stages, false, false) { - return false; + *passes += 1; + // Whether the device was there before the pass: a view that removes + // it is named below. + static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); + for (n, &index) in slots.iter().enumerate() { + ranges.remove(&index); + let Some(handle) = heap.handle(index) else { + continue; + }; + let Some(view) = host.mirror(index, handle, true) else { + continue; + }; + // Every 64 views while the device lives (a cheap query). + if alive + && n % 64 == 63 + && let Some(why) = crate::descriptor::host::device_removed() + { + alive = false; + GONE.store(true, Ordering::Relaxed); + let last: Vec = slots[n - 63..=n] + .iter() + .filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}"))) + .map(|s| s.chars().take(200).collect()) + .collect(); + tracing::error!(why, slot = index, "the host device went while buffer views of the heap were made; one of: {last:#?}"); + crate::host::log_removal_context(); + } + // The copy the slot shows (`buffer_copy`), not the one the + // view's range alone would find. + let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(&view) else { + continue; + }; + #[cfg(feature = "diagnostics")] + if host.shows(index, &shadow.buffer) == Some(false) { + HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); + } + ranges.insert(index, (shadow, address, address + len)); + } + let views = ranges.len() as u32; + // Per host copy, the span its picked views cover. + let mut spans: std::collections::HashMap, u64, u64)> = + std::collections::HashMap::new(); + for (shadow, from, to) in ranges.values() { + let key = std::sync::Arc::as_ptr(shadow) as usize; + let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to)); + span.1 = span.1.min(*from); + span.2 = span.2.max(*to); + } + drop(kept); + let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum(); + // Memory that is not write-watched is copied whole by every refresh. + // It was once refreshed only every 120 frames (unmapped pages read + // one by one cost 14 GB a frame in run 11, before they were + // remembered): streamed geometry then drew from stale buffers, and + // the garbage ended runs (the card stopped answering 14-90 frames + // into the opening cutscene; with every frame it ran on). The pass + // costs some 30 ms a frame this way. + static WHOLE: std::sync::Mutex>> = std::sync::Mutex::new(None); + let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); + let whole = whole.get_or_insert_with(Default::default); + for (shadow, from, to) in spans.values() { + if shadow.unwatched() { + // By the copy's number: a copy made where one let go was + // (`shadow::let_go_idle`) has never been refreshed. + let key = shadow.id() as usize; + // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame). + static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + let every = *EVERY.get_or_init(|| { + std::env::var("VICTORY_UNWATCHED_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1) + }); + match whole.get(&key) { + Some(&last) if frame < last + every => continue, + _ => { + whole.insert(key, frame); + } + } + } + shadow.refresh(list, *from, to - from); + } + self.heap_textures(list, heap, host); + HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); + HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + static LOGGED: AtomicU64 = AtomicU64::new(0); + // The first pass and every growth of the set by half. + let seen = LOGGED.load(Ordering::Relaxed); + if u64::from(views) > seen + seen / 2 { + LOGGED.store(u64::from(views), Ordering::Relaxed); + tracing::info!( + slots = slots.len(), + views, + copies = spans.len(), + mb = bytes >> 20, + ms = started.elapsed().as_millis(), + "buffer views of the heap made ready for shaders that pick them by index" + ); } - let l = &list.list; - // SAFETY: an open list; `output` is live and in non-pixel shader - // resource state when the draw is recorded. - unsafe { - l.SetGraphicsRootShaderResourceView(emu.draw_srv_param, buffers.output_gpu); - l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + Some(gpu) + } + + /// Runs the pass that uploads textures picked by index + /// ([`State::heap_textures`]) where nothing has asked for it yet + /// ([`early_budgets`]): once a frame for a few milliseconds, at the + /// frame's first draw with a view heap set, and with a larger budget + /// of its own before every draw whose pixel shader is one of the + /// title's bake programs. The uploads are recorded into `list` ahead + /// of the draw being bound, as the world's pass records them. + fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) { + let (early_ms, bake_ms) = early_budgets(); + if compute || (early_ms == 0 && bake_ms == 0) { + return; + } + let bake = bake_ms > 0 + && p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str())); + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + // The milliseconds this frame's bake draws have taken so far: a + // frame has several, and together they get `bake_ms`. + static BAKED_MS: AtomicU64 = AtomicU64::new(0); + let frame = crate::frame::current(); + let first = FRAME.swap(frame, Ordering::Relaxed) != frame; + if first { + BAKED_MS.store(0, Ordering::Relaxed); + } + let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); + let budget = if bake && left > 0 { + // What a bake may read must be there now: up to 2 GiB. + (left, 2 << 30) + } else if first && early_ms > 0 { + (early_ms, 64 << 20) + } else { + return; + }; + let Some(heap) = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers()) + else { + return; + }; + let Some(host) = heap.host() else { + return; + }; + let bake = bake && left > 0; + let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1; + if bake && n.is_power_of_two() { + let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); + tracing::info!( + frame, + bakes = n, + queued_at_the_last_pass = slots, + due_at_the_last_pass = due, + uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), + "a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)" + ); + } + let began = std::time::Instant::now(); + PASS_BUDGET.set(Some(budget)); + self.heap_textures(list, heap, host); + PASS_BUDGET.set(None); + if bake { + BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); + } + } + + /// The queue's side of the card accounting line + /// (`crate::resource::card_accounting`, which says what the line + /// holds): the slots that are due, by what their texture has on the + /// card. Off unless `VICTORY_CARD_ACCOUNTING=1`; then at the first pass + /// that finds the card without room, and every five seconds after it. + /// Nothing is made, uploaded or counted as used here. For 18,000 due + /// slots: 18,000 looks at a title slot and at the texture it views, a + /// lock each, some milliseconds of the thread that records the frame. + fn card_accounting( + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + frame: u64, + room: bool, + ) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ACCOUNTING").is_some_and(|v| v == "1")) { + return; + } + // When the next line is due (0: none yet, the card has had room). + static NEXT: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms().max(1); + let next = NEXT.load(Ordering::Relaxed); + let due_now = if next == 0 { !room } else { now >= next }; + if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + // Due slots; of them uploaded before; of them viewing nothing the + // title fills; and the textures (each once) whose host copy is + // alive, with their bytes on the card. + let mut due = [0u64; 5]; + // Textures (each once) that never had a host copy, and ones whose + // host copy was let go: where their memory is, and its bytes. + let (mut never, mut gone) = (Vec::new(), Vec::new()); + let mut seen = std::collections::BTreeSet::new(); + for (index, uploaded) in host.texture_slots_all_due(frame) { + due[0] += 1; + due[1] += u64::from(uploaded); + let state = match heap.handle(index).and_then(crate::descriptor::view) { + Some(View::Placed(false, resource, desc)) if resource[0] != 1 => { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + match crate::resource::placed_known(address, &resource) { + Some(texture) => crate::resource::copy_state(texture), + // No title texture was made for it: the pass never + // got as far as making one. + None => Some((0, crate::resource::placed_bytes(&resource).unwrap_or(0), address)), + } + } + Some(View::Shader(object, _)) if crate::resource::title_fills(object as This) => { + crate::resource::copy_state(object as This) + } + _ => None, + }; + let Some((state, bytes, memory)) = state else { + due[2] += 1; + continue; + }; + if !seen.insert(memory) { + continue; + } + match state { + 2 => { + due[3] += 1; + due[4] += bytes; + } + 1 => gone.push((memory, bytes)), + _ => never.push((memory, bytes)), + } + } + crate::resource::card_accounting(room, due, never, gone); + } + + /// The texture side of [`State::heap_buffers`]: textures the title fills + /// itself (streamed pages, layout-library copies) whose views sit in the + /// view heap are created (placed textures have no host texture until + /// something reads them) and uploaded, as a table read would do, for + /// shaders that pick them by a computed index. Within a budget of bytes + /// per frame and in all; the rest waits for later lists and frames. + /// The most recently written slots first (`TextureQueue::due`); slots + /// draws read through tables are not in the queue. + /// shortcut: uploaded once, and again only when the title rewrites the + /// slot. A placed texture not all mapped yet is uploaded with what is + /// there and looked at again (1, 2, 4, ... frames later, at most about + /// a second): uploaded again when more of it is mapped. Pages mapped + /// in place of others, and contents changed with no descriptor write, + /// are missed (hook the page-mapping events for those). + /// `VICTORY_HEAP_TEXTURES=0` turns it off. + fn heap_textures( + &self, + list: &HostList, + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + ) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) { + return; + } + /// Bytes of texture memory staged per frame. + // `VICTORY_TEXTURE_STAGE_MB` raises it: a backlog of tens of thousands of + // textures (a scene's first minutes) then drains in fewer frames. + static PER_FRAME_MB: std::sync::OnceLock = std::sync::OnceLock::new(); + let per_frame: u64 = *PER_FRAME_MB.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_STAGE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(192) + }) << 20; + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + static SPENT: AtomicU64 = AtomicU64::new(0); + let frame = crate::frame::current(); + if FRAME.swap(frame, Ordering::Relaxed) != frame { + SPENT.store(0, Ordering::Relaxed); + } + // No more of them are made while the card has no room + // (`resource::room`): by what is alive now, not by what was ever + // staged (4 GB in all, after which later textures stayed empty for + // the run). The ones nothing names any more are let go, which + // makes room again: so the slots are still looked at (the pass + // returned here, and a slot whose texture had been streamed out + // kept its host copy for as long as the card was full). + let room = crate::resource::room(); + if !room { + HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed); + once!("textures picked by index: the card has no room for more; they wait"); + } + let mut refused = 0; + // Slots whose texture's memory the runtime mapped, unmapped or + // wrote since the last pass are due again. + host.texture_slots_remapped(frame); + let (due, census) = host.texture_slots_due(frame, 4096); + HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); + for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { + count.store(now, Ordering::Relaxed); + } + // Where the card's memory is, and what the due slots would need + // (`VICTORY_CARD_ACCOUNTING=1`; a line when the card first has no + // room, and every five seconds after it). + Self::card_accounting(heap, host, frame, room); + // The frames in about four seconds, between 16 and 256: how long a + // slot with nothing to upload waits at most for its next look. In + // frames alone it was 120: four minutes at the opening cutscene's + // half a frame per second, while the title streams by the clock. + // (About a second before the runtime told of the memory it maps: + // the looks are now only for what that does not tell.) + static PASSED: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms(); + let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1); + let most = (4000 / took).clamp(16, 256); + // What a table entry of a texture a shader samples says. + let sampled = UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }; + // Also within a time per pass: the pass runs on a thread that + // records the frame, and making and staging 192 MB of textures took + // 1.6-2.2 s of each of the world's first twenty frames (run 20). + // The rest waits for the next frames, as it does past the bytes. + static SPAN_MS: std::sync::OnceLock = std::sync::OnceLock::new(); + let span = std::time::Duration::from_millis(*SPAN_MS.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_STAGE_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(250) + })); + // A backlog (a scene's first minutes: 22,000 slots due, 2-3 minutes of black + // surfaces at 192 MB a frame) gets three times the bytes and the time until it + // drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget. + static CATCHUP: std::sync::OnceLock = std::sync::OnceLock::new(); + let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0")); + let (per_frame, span) = if catchup && due.len() >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) }; + // A run made early (`State::early_textures`) has a budget of its + // own: its bytes on top of what the frame has spent so far. + // (Not `most`: that is the longest wait between looks, used below.) + let (span, bytes_at_most) = match PASS_BUDGET.get() { + Some((ms, bytes)) => { + (std::time::Duration::from_millis(ms), SPENT.load(Ordering::Relaxed).saturating_add(bytes)) + } + None => (span, per_frame), + }; + let began = std::time::Instant::now(); + for (index, write) in due { + if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span { + break; + } + // A placed texture whose memory is not mapped (not streamed in + // yet, or streamed out again: the heap keeps tens of thousands + // of such views) gets no host texture; looked at again soon (a + // title writes a texture's view before its pages are mapped, + // and the pass runs early in a frame). One of which some is + // mapped (a texture streaming in: its smaller mips lie at the + // start of its memory and arrive first) is uploaded with what + // is there, and again when more is. (It was uploaded again + // every 120 frames, changed or not; and asked by its first + // page alone, one whose first page is the one missing counted + // as not there.) + // A slot uploaded whole is looked at again a few times + // (`RECHECK_FRAMES`): the title writes a texture's view, and + // may fill the texture's memory itself only afterwards, with + // no descriptor write and nothing from the runtime to tell of + // it. The host copy then kept what the memory held at the + // first look for the rest of the run. The look reads 48 KiB; + // only a changed texture is uploaded again. + // `VICTORY_HEAP_RECHECK=0`: uploaded once, as before. + if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) { + if crate::texture::fingerprint(at, len) == print { + HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed); + match RECHECK_FRAMES.get(usize::from(looks) + 1) { + Some(wait) => { + host.texture_slot_recheck(index, write, frame + wait, (at, len), print, looks + 1, uploaded) + } + None => host.texture_slot_done(index, write, None), + } + continue; + } + let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed); + if n < 200 || n.is_multiple_of(1000) { + tracing::warn!( + slot = index, + address = format_args!("{at:#x}"), + bytes = len, + frames_after_upload = frame.saturating_sub(uploaded), + looks, + changed = n + 1, + "a texture picked by index changed after its upload with nothing to tell of it: uploaded again" + ); + } + } + let mut partly = None; + if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let len = crate::resource::placed_bytes(&resource).unwrap_or(1); + let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize); + if mapped == 0 { + HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed); + // Streamed out: what the slot showed is let go. + host.texture_slot_gone(index); + host.texture_slot_later(index, write, frame, most); + continue; + } + if mapped < len { + if mapped <= host.texture_slot_mapped(index) { + HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed); + host.texture_slot_later(index, write, frame, most); + continue; + } + if !crate::texture::committed(address as *const u8, 1) { + HEAP_TEXTURES_PARTLY[2].fetch_add(1, Ordering::Relaxed); + } + partly = Some(mapped); + } + } + // A texture object the host renders to or writes holds the + // host's own contents: nothing to bring up to date, and this + // pass is no use of it (its host copy is made when something + // uses it, and its slots then: `descriptor::make_waiting`). + if let Some(View::Shader(object, _)) = heap.handle(index).and_then(crate::descriptor::view) + && crate::resource::buffer_bytes(object as This).is_none() + && !crate::resource::title_fills(object as This) + { + host.texture_slot_done(index, write, None); + continue; + } + // From here on a host texture is made: not without room. The + // slot stays due. + // Not so a slot already made from this very view: its host + // texture exists, and uploading it again takes none of the + // card's memory. It was refused all the same, so a texture the + // title filled after its first upload kept its empty host copy + // from the moment the card reached the line, which is the first + // world frame in eight launches of nine: the same slots were + // found changed again at every pass and never uploaded (run + // 179: 33,000 such findings), and the main character's face + // had its colour only in the launches that entered the world + // under the line. `VICTORY_REUPLOAD_WHEN_FULL=0`: refused, as + // before. + if !room { + let has_its_texture = reupload_when_full() + && heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle)); + if !has_its_texture { + refused += 1; + if refused > 256 { + break; + } + continue; + } + let n = HEAP_TEXTURES_REUPLOADED_FULL.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_multiple_of(500) { + tracing::info!( + so_far = n, + slot = index, + "a texture already on the card is brought up to date although the card has no room for new ones" + ); + } + } + let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true)); + let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); + let resource = match placed.as_ref().or(view.as_ref()) { + Some(&View::Shader(resource, _)) => resource as This, + _ => { + host.texture_slot_done(index, write, None); + continue; + } + }; + let title_fills = crate::resource::host_resource(resource).is_some_and(crate::texture::title_written); + if !title_fills { + // a render target, a depth or unordered access texture: the host's own + host.texture_slot_done(index, write, None); + continue; + } + // A texture that has a staging buffer now is one draws read + // through a table: they upload it, and check it at every + // submission that samples it. + let tabled = crate::texture::is_staged(resource); + if let Some(view) = &view { + readable(list, sampled.kind, view); + } + // A texture view the host refuses removes the device: name it. + static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !GONE.load(Ordering::Relaxed) + && let Some(why) = crate::descriptor::host::device_removed() + { + GONE.store(true, Ordering::Relaxed); + let text: String = format!("{view:?}").chars().take(300).collect(); + tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}"); + crate::host::log_removal_context(); + return; + } + let (bytes, whole) = crate::texture::staged(resource).unwrap_or((0, true)); + // Not all of it there: looked at again next frame, and from + // then on as a slot with nothing new (a placed texture: until + // more of it is mapped; a texture object at an address the + // title mapped: again in 120 frames, as before). + let again = match partly { + Some(mapped) => Some((frame + 1, mapped)), + None => (!whole).then_some((frame + 120, 0)), + }; + if again.is_some() { + HEAP_TEXTURES_PARTLY[1].fetch_add(1, Ordering::Relaxed); + } + if tabled { + // Nothing was staged here, so nothing is counted or spent, + // and the staging buffer stays: taking it away made the + // next draw that reads the texture through a table stage, + // detile and upload all of it once more. + HEAP_TEXTURES_TABLED.fetch_add(1, Ordering::Relaxed); + host.texture_slot_done(index, write, again); + continue; + } + // Uploaded: the list holds the staging buffer until it has run; + // a table read, or the next look at a texture not all mapped + // yet, makes it anew. (Kept for those until now: every partly + // streamed texture of the heap held a staging buffer of its full + // size for good.) + let memory = if again.is_none() && heap_recheck() { + crate::texture::staged_memory(resource) + } else { + None + }; + crate::texture::unstage(resource); + SPENT.fetch_add(bytes, Ordering::Relaxed); + HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed); + HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed); + match memory { + // Whole and uploaded: looked at again (see above). + Some((at, len)) => { + let print = crate::texture::fingerprint(at, len); + host.texture_slot_recheck(index, write, frame + RECHECK_FRAMES[0], (at, len), print, 0, frame); + } + None => host.texture_slot_done(index, write, again), + } } - self.ensure_targets(list); - true } - fn restore_mesh_emu_state(&mut self, list: &HostList) { - if self.topology != D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32 { - self.set_topology(list, self.topology); - } - self.host_pipeline = 0; - self.host_roots = [0; 2]; + /// For the frame listing, after a dropped dispatch's line: its group + /// counts and the compute root arguments it was recorded with (root + /// constants as hex dwords, root views with the title buffer they + /// point into). A program that does not translate has no bindings to + /// list; these say which memory it would have read and written (the + /// ray-tracing structure builder passes its buffers this way). + #[cfg(feature = "diagnostics")] + fn list_dropped_roots(&self, groups: [u32; 3]) { + crate::capture::op(0, || { + use std::fmt::Write; + let [x, y, z] = groups; + let mut text = format!(" its roots ({x}x{y}x{z}):"); + for (slot, root) in self.compute.iter().enumerate() { + match root { + Root::None => {} + Root::Table(a) => { + let _ = write!(text, " {slot}=table {a:#x}"); + } + Root::Constants(v) => { + let _ = write!(text, " {slot}=constants {:x?}", &v[..v.len().min(48)]); + } + Root::View(a) => { + let _ = write!(text, " {slot}=view {a:#x}"); + match crate::shadow::extent(*a) { + Some((start, len)) => { + let _ = write!(text, " in buffer {start:#x}+{len:#x}"); + } + None => text.push_str(" in no buffer"), + } + } + } + } + text + }); } /// Runs a dispatch on the host. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) { + // It may write the arguments a window holds clamped. + self.window = None; #[cfg(feature = "diagnostics")] if crate::pipeline::is_skipped(self.pipeline as This) { DROPPED.fetch_add(1, Ordering::Relaxed); crate::pipeline::note_drop(self.pipeline as This); return; } + // The ray-tracing structure builder's stages run all or none. + if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + crate::pipeline::note_why("a stage of the ray-tracing structure builder, which is off".to_owned()); + self.list_dropped_roots([x, y, z]); + } + return; + } let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { once!( pipeline = format_args!("{:#x}", self.pipeline), @@ -823,7 +2000,10 @@ impl State { ); DROPPED.fetch_add(1, Ordering::Relaxed); #[cfg(feature = "diagnostics")] - crate::pipeline::note_drop(self.pipeline as This); + { + crate::pipeline::note_drop(self.pipeline as This); + self.list_dropped_roots([x, y, z]); + } return; }; if !p.compute { @@ -832,19 +2012,24 @@ impl State { } if !self.bind(list, p, true) { DROPPED.fetch_add(1, Ordering::Relaxed); + // A stage of the structure builder that cannot be bound is a + // dropped stage: the others stop too. + if crate::pipeline::is_builder(self.pipeline as This) { + crate::pipeline::builder_off("one of its dispatches could not be bound"); + } return; } #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); - list.flush_barriers(); // SAFETY: an open list with everything set. unsafe { list.list.Dispatch(x, y, z) }; DISPATCHED.fetch_add(1, Ordering::Relaxed); } /// What a draw or dispatch runs, for the device-removed report - /// (diagnostics): the pipeline, then each stage's bound user data, - /// descriptor table bases, root view addresses and known table entries. + /// (diagnostics): the pipeline, then per stage the user data it gets + /// (with the view at that heap index, if one is), the host addresses + /// of its root views and the views its tables name. #[cfg(feature = "diagnostics")] fn op_text(&self, kind: String, compute: bool) -> String { use std::fmt::Write; @@ -852,13 +2037,50 @@ impl State { return kind; }; let mut text = format!("{kind} {}", p.name); - for (stage, bound) in p.stages.iter().zip(&self.bound_user_data) { + // What it draws into (a dispatch writes through its views below). + if !compute { + let described = |t: usize| { + crate::resource::host_made(t as This).map(|r| { + // SAFETY: a live resource. + let d = unsafe { r.GetDesc() }; + format!("{t:#x} {}x{} f{}", d.Width, d.Height, d.Format.0) + }) + }; + let targets: Vec = self.targets.iter().filter_map(|&t| described(t)).collect(); + let _ = write!(text, " targets {targets:?} depth {:?} state [{}]", described(self.depth), p.state); + // The title's scissor and viewport at this draw (the first of + // each): the title draws what it sees through a + // portal (a window, from inside a room) under the portal's + // rectangle, and the listing did not say which draws those are. + if let Some(r) = self.scissors.first() { + let _ = write!(text, " scissor [{} {} {} {}]", r.left, r.top, r.right, r.bottom); + } + if let Some(v) = self.viewports.first() { + let _ = write!( + text, + " viewport [{} {} {} {} depth {}..{}]", + v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth + ); + } + } + let views = (self.heaps[0] != 0) + .then(|| crate::descriptor::heap(self.heaps[0] as This).host()) + .flatten(); + for stage in &p.stages { let t = stage.translated(); let _ = write!(text, " | {}:", stage.shader.hash); for u in &t.host.user_data { - self.note_user_data(&mut text, compute, u, bound); + let v = match u.root { + RootType::Other(kind) => self.host_word(compute, kind, u.slot, u.dword, None), + _ => self.user_value(compute, u.slot, u.root, u.dword), + }; + let _ = write!(text, " u{}={v:#x}", u.index); + let index = if u.root == RootType::Table { v / 32 } else { v }; + if let Some(slot) = views.and_then(|h| h.describe_slot(index)) { + let _ = write!(text, " [heap {index}: {slot}]"); + } } - for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs) { + for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs).chain(&stage.root_uavs) { if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) { let host = crate::shadow::find(*address, 1) .map(|s| (s.gpu(*address), s.left(*address))); @@ -866,77 +2088,212 @@ impl State { } } } - let _ = write!(text, " title tables {:?}", self.reads(compute)); + let _ = write!(text, " tables {:?}", self.reads(compute)); + if !compute && !list_slots().is_empty() { + text.push_str(&self.slots_text()); + } text } + /// For the frame listing, after a draw whose shader `VICTORY_LIST_SLOTS` + /// names: the heap slots it will pick textures from by index, and what + /// the title and the host hold there (one `~slot` line each), with the + /// words they were read from (`~raw` lines, to decode offline what is + /// not decoded here). + /// + /// Where the slots are, for the title's character shaders + /// (`PS_DeferredPedTexturedNC`, from their native code): in the small + /// buffers and constants of the draw's own table (every word of those + /// that names a texture view gets a line); in the material record, at + /// the byte offset the draw's constants (table 1, dword 56) hold at + /// 0x1c, of the buffer at table 0, dword 160; and in the record at the + /// byte offset the second root constant holds of the buffer at table 0, + /// dword 688. A word that is a small number by chance and names a + /// texture gets a line too. #[cfg(feature = "diagnostics")] - fn note_user_data( - &self, - text: &mut String, - compute: bool, - data: &victory_shader::emit::UserData, - bound: &BoundUserData, - ) { + fn slots_text(&self) -> String { use std::fmt::Write; - let Some(&value) = bound.values.get(data.index as usize) else { - return; + const MATERIALS: u32 = 160; + const GLOBAL: u32 = 688; + const DRAW_CONSTANTS: u32 = 56; + let wanted = list_slots(); + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return String::new(); }; - let _ = write!(text, " u{}={value:#x}", data.index); - if data.root != RootType::Table { - return; - } - if bound - .rebuilt_tables + let Some(stage) = p.stages.iter().find(|s| wanted.iter().any(|w| s.shader.hash.starts_with(w.as_str()))) + else { + return String::new(); + }; + let Some(heap) = self + .heaps .iter() - .any(|&(slot, _)| slot == data.slot) + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers()) + else { + return String::new(); + }; + let t = stage.translated(); + let mut text = String::new(); + let entry = |slot: u8, dwords: u32| -> Option { + let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(slot)) else { + return None; + }; + crate::descriptor::view(table + u64::from(dwords) * 4) + }; + let mut material = None; + for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind != ResourceType::Sampler) { + let label = format!("s{}+{}", u.slot, u.table_offset_dwords); + let Some(view) = entry(u.slot, u.table_offset_dwords) else { + let _ = write!(text, "\n ~table {label} no view"); + continue; + }; + let range = match &view { + View::Constant(address, size) => Some((*address, u64::from(*size))), + other => crate::descriptor::host::buffer_range(other), + }; + match range { + // A small buffer or constants: its words. + Some((address, len)) if len <= 2048 => { + Self::slot_words(&mut text, heap, &label, address, len as usize); + if u.slot == 1 && u.table_offset_dwords == DRAW_CONSTANTS && len >= 0x20 { + let mut word = [0u8; 4]; + if crate::host::read_into((address + 0x1c) as *const u8, &mut word) { + material = Some(u32::from_le_bytes(word)); + } + } + } + Some(_) => {} + // A texture read through the table: the title slot it sits in. + None => { + let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(u.slot)) else { + continue; + }; + match heap.index(table + u64::from(u.table_offset_dwords) * 4) { + Some(index) => text.push_str(&Self::slot_line(heap, &format!("table:{label}"), 0, index)), + None => { + let _ = write!(text, "\n ~table {label} title=[{}]", view_state(Some(&view))); + } + } + } + } + } + let uses = |slot: u8, dwords: u32| { + t.used.iter().any(|u| u.root == RootType::Table && u.slot == slot && u.table_offset_dwords == dwords) + }; + if let Some(at) = material + && uses(0, MATERIALS) + && let Some((base, len)) = entry(0, MATERIALS).as_ref().and_then(crate::descriptor::host::buffer_range) + { + let at = u64::from(at); + let _ = write!(text, "\n ~material record at {at:#x} of the buffer at {base:#x} bytes {len}"); + if at + 64 <= len { + Self::slot_words(&mut text, heap, "M", base + at, 64); + } + if at + 1936 + 512 <= len { + Self::slot_words(&mut text, heap, "M+1936", base + at + 1936, 512); + } + } + if uses(0, GLOBAL) + && let Some(slot) = t.used.iter().find(|u| u.root == RootType::Constants).map(|u| u.slot) + && let Some(Root::Constants(words)) = self.roots_ref(false).get(usize::from(slot)) + && let Some(&at) = words.get(1) + && let Some((base, len)) = entry(0, GLOBAL).as_ref().and_then(crate::descriptor::host::buffer_range) { - // Rebuilt tables use dynamic view slots, which have no mirror - // record. The offset is in 32-byte console view descriptors. - let _ = write!(text, " [rebuilt view table base {}]", value / 32); + let at = u64::from(at); + let _ = write!(text, "\n ~root constants {words:08x?}: record at {at:#x} of the buffer at {base:#x} bytes {len}"); + if at + 64 <= len { + Self::slot_words(&mut text, heap, "G", base + at, 64); + } + } + text + } + + /// Up to 512 bytes of title memory at `address` as hex words (a `~raw` + /// line), and a `~slot` line for every word of them that names a + /// texture view in `heap`. + #[cfg(feature = "diagnostics")] + fn slot_words(text: &mut String, heap: &crate::descriptor::Heap, label: &str, address: u64, len: usize) { + use std::fmt::Write; + let mut bytes = vec![0u8; len.min(512) & !3]; + if bytes.is_empty() || !crate::host::read_into(address as *const u8, &mut bytes) { + let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}: unreadable"); return; } - let table = match self.roots_ref(compute).get(usize::from(data.slot)) { - Some(Root::Table(handle)) => self - .heap_of(*handle) - .and_then(|heap| heap.index(*handle).map(|index| (heap, index))), - _ => None, - }; - if let Some((heap, index)) = table { - let kind = if heap.samplers() { "sampler" } else { "view" }; - let _ = write!(text, " [{kind} table base {index}"); - if let Some(record) = heap.host().and_then(|h| h.describe_slot(index)) { - let _ = write!(text, ": {record}"); + let words: Vec = + bytes.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect(); + let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}:"); + for w in &words { + let _ = write!(text, " {w:08x}"); + } + for (i, &index) in words.iter().enumerate() { + let names = index != 0 + && heap + .handle(index) + .and_then(crate::descriptor::view) + .as_ref() + .is_some_and(crate::descriptor::host::is_texture_view); + if names { + text.push_str(&Self::slot_line(heap, label, i * 4, index)); } - text.push(']'); - } else { - text.push_str(" [unbound table]"); + } + } + + /// One `~slot` line: where the slot number was read (`from`, byte + /// `at`), what the title's heap holds in slot `index` with the state + /// of that texture ([`view_state`]), what the host slot was made from, + /// and what the queue of textures picked by index knows of it. + #[cfg(feature = "diagnostics")] + fn slot_line(heap: &crate::descriptor::Heap, from: &str, at: usize, index: u32) -> String { + let title = heap.handle(index).and_then(crate::descriptor::view); + let host: String = heap + .host() + .and_then(|h| h.describe_slot(index)) + .unwrap_or_else(|| "none".into()) + .chars() + .take(90) + .collect(); + let queue = match heap.host() { + Some(h) => h.texture_slot_state(index, crate::frame::current()), + None => "no host heap".into(), + }; + format!( + "\n ~slot from={from}+{at:#x} slot={index} title=[{}] host=[{host}] queue=[{queue}]", + view_state(title.as_ref()) + ) + } + + /// A mesh draw under `VICTORY_MESH_TEST=scissor` rasterises one pixel: + /// the scissors before it (`on`), the title's after it. + fn mesh_scissor(&self, list: &HostList, on: bool) { + if mesh_test() != 2 { + return; + } + if on { + let one = RECT { left: 0, top: 0, right: 1, bottom: 1 }; + crate::draw::scissors(list, &vec![one; self.scissors.len().max(1)]); + } else if !self.scissors.is_empty() { + crate::draw::scissors(list, &self.scissors); } } /// Runs a mesh dispatch of `x` groups on the host (the title's mesh /// programs are one-dimensional). pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) { + self.window = None; #[cfg(feature = "diagnostics")] self.trace("mesh", x, 0); - if let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) - && p.mesh_emu.is_some() - { - if !self.dispatch_mesh_emulated(list, p, x) { - DROPPED.fetch_add(1, Ordering::Relaxed); - #[cfg(feature = "diagnostics")] - dropped(self.pipeline); - } - return; - } - let ran = self.prepare_for(list, false, true) + let ran = mesh_test() != 1 + && mesh_kept(self.pipeline) + && self.prepare_for(list, false, true) && match list.list.cast::() { Ok(l6) => { #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("mesh {x}"), false)); - list.flush_barriers(); + self.mesh_scissor(list, true); // SAFETY: an open list with everything set. unsafe { l6.DispatchMesh(x, 1, 1) }; + self.mesh_scissor(list, false); DRAWN.fetch_add(1, Ordering::Relaxed); true } @@ -949,78 +2306,72 @@ impl State { } } - fn dispatch_mesh_emulated(&mut self, list: &HostList, p: &HostPipeline, x: u32) -> bool { - #[cfg(feature = "diagnostics")] - if crate::pipeline::is_skipped(self.pipeline as This) { - return false; - } - let Some(emu_pipe) = &p.mesh_emu else { - return false; - }; - if x == 0 { - DRAWN.fetch_add(1, Ordering::Relaxed); - return true; - } - let Some(buffers) = crate::mesh_emu::buffers() else { - return false; - }; - let group_cap = buffers.group_cap(emu_pipe.emu.group_bytes()); - if group_cap == 0 { - once!( - group_bytes = emu_pipe.emu.group_bytes(), - "mesh emulation buffer too small for one group" - ); - return false; - } - let mut base = 0u32; - while base < x { - let chunk = (x - base).min(group_cap); - if !self.bind_emulated_cs(list, p, buffers, base) { - self.restore_mesh_emu_state(list); - return false; + /// The walls trace (`crate::host::walls_trace`): one log line per + /// frame with the draws of its main pass (four or more colour targets) + /// by scissor rectangle, and how often each of the title's culling + /// programs was dispatched. The title clips what it draws + /// through a window or door to that opening's rectangle while it holds + /// the camera to be in a room (run 182, frame 1529: 1,386 draws under + /// `531 0 1789 1337`); in a launch without the room's walls the same + /// shot has no such rectangle (run 187, frame 1414). The line shows + /// the frame in which that changes. + fn walls_census(&self, p: &HostPipeline, compute: bool) { + const CULL: [(&str, &str); 9] = [ + ("55679a0547649d0b", "tree"), + ("89d08e561897d4e5", "tree_imposter"), + ("9209777e8face9dd", "grass"), + ("17af15c4015cb4b6", "prop"), + ("fdd56d97a806bcca", "prop_nocull"), + ("42f717f1b4d18e94", "simple"), + ("1c4b3c0547e3e6fa", "slod"), + ("9146291b38ea9ce1", "meshlet_args"), + ("42683eebec081520", "depth_pyramid_cpu_occlusion"), + ]; + type Census = (u64, std::collections::BTreeMap<[i32; 4], u32>, [u32; 9]); + static CENSUS: std::sync::Mutex = + std::sync::Mutex::new((u64::MAX, std::collections::BTreeMap::new(), [0; 9])); + let frame = crate::frame::current(); + let mut census = CENSUS.lock().unwrap_or_else(|e| e.into_inner()); + if census.0 != frame { + let draws: u32 = census.1.values().sum(); + if draws > 0 { + let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect(); + rects.sort_unstable_by_key(|a| std::cmp::Reverse(a.1)); + let scissors: Vec = rects + .iter() + .take(5) + .map(|(r, n)| format!("{} {} {} {} x{n}", r[0], r[1], r[2], r[3])) + .collect(); + let counts = census.2; + let culling: Vec = CULL + .iter() + .zip(counts) + .filter(|(_, n)| *n > 0) + .map(|(c, n)| format!("{}={n}", c.1)) + .collect(); + tracing::info!( + frame = census.0, + main_pass_draws = draws, + rectangles = rects.len(), + scissors = ?scissors, + culling = ?culling, + "walls trace: the frame's main pass by scissor rectangle, and its culling dispatches" + ); } - #[cfg(feature = "diagnostics")] - list.note_op(|| self.op_text(format!("mesh-emu {chunk} (base {base})"), false)); - list.flush_barriers(); - // SAFETY: open list with the emulated compute pipeline bound and - // `output` in unordered-access state. - unsafe { - list.list.Dispatch(chunk, 1, 1); - list.list.ResourceBarrier(&[transition( - &buffers.output, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - )]); - } - if !self.bind_emulated_gfx(list, p, buffers) { - // SAFETY: restore `output` for the next compute step. - unsafe { - list.list.ResourceBarrier(&[transition( - &buffers.output, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - )]); + census.0 = frame; + census.1.clear(); + census.2 = [0; 9]; + } + if compute { + for (i, c) in CULL.iter().enumerate() { + if p.stages.iter().any(|s| s.shader.hash.as_str() == c.0) { + census.2[i] += 1; } - self.restore_mesh_emu_state(list); - return false; - } - list.flush_barriers(); - // SAFETY: open list with the unpack graphics pipeline bound and - // `output` readable as a shader resource. - unsafe { - list.list - .DrawInstanced(chunk * emu_pipe.emu.max_primitives * 3, 1, 0, 0); - list.list.ResourceBarrier(&[transition( - &buffers.output, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - )]); } - base += chunk; + } else if self.targets.iter().filter(|&&t| t != 0).count() >= 4 { + let r = self.scissors.first().map_or([0; 4], |r| [r.left, r.top, r.right, r.bottom]); + *census.1.entry(r).or_insert(0) += 1; } - self.restore_mesh_emu_state(list); - DRAWN.fetch_add(1, Ordering::Relaxed); - true } fn roots_ref(&self, compute: bool) -> &Vec { @@ -1043,7 +2394,11 @@ impl State { return; }; if let Some(view) = host.mirror(index, handle, true) { - readable(list, u, &view); + readable(list, u.kind, &view); + // Up to date by this draw: not the texture pass's to make. + if crate::descriptor::host::is_texture_view(&view) { + host.texture_slot_tabled(index, true); + } } } @@ -1052,19 +2407,19 @@ impl State { /// the constant data copied to upload memory when the list is /// submitted: the host wants constant buffers 256-byte aligned, the /// console only 16. Returns those tables' new byte offsets by root - /// parameter; the other tables' slots are made from the title's. If - /// the heap cannot fit a fresh table, the bind must release its reservations. + /// parameter; the other tables' slots are made from the title's. /// /// Within a list, the same table holding the same descriptors is made /// once: its constant data is copied at submission either way, and the /// big tables the world binds would otherwise take hundreds of slots per /// draw, wrapping the dynamic slots onto lists not yet submitted. - fn tables( + pub(crate) fn tables( &mut self, list: &HostList, used: &[UsedResource], + indexed: &[RootIndexedView], compute: bool, - ) -> Option> { + ) -> Vec<(u8, u32)> { let tables = |u: &&UsedResource| u.root == RootType::Table; let mut fresh: Vec = used .iter() @@ -1089,13 +2444,7 @@ impl State { let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else { continue; }; - if index >= host.count() - || (u.kind == ResourceType::Srv - && crate::descriptor::view(end) - .as_ref() - .and_then(crate::descriptor::host::unaligned_srv) - .is_some()) - { + if index >= host.count() { fresh.push(u.slot); } } @@ -1119,14 +2468,42 @@ impl State { let Some(heap) = self.heap_of(table) else { continue; }; + if heap.samplers() || (table - heap.start) % 32 != 0 { + continue; + } let Some(host) = heap.host() else { continue; }; + let mut selected: Vec = indexed + .iter() + .filter(|index| index.table_slot == slot) + .map(|index| { + let constant = self.user_value( + compute, + index.constant_slot, + RootType::Constants, + index.constant_dword, + ); + // The shader adds i32 byte offsets and shifts by 5. + index.byte_offset.wrapping_add(constant << index.shift) / 32 + }) + .collect(); + selected.sort_unstable(); + selected.dedup(); let n = entries .iter() - .map(|u| u.table_offset_dwords / 8 + 1) + .map(|u| u.table_offset_dwords / 8) + .chain(selected.last().copied()) .max() - .unwrap_or(1); + .unwrap_or(0) + + 1; + let last = table.checked_add(u64::from(n - 1) * 32); + if n > crate::descriptor::host::DYNAMIC + || last.and_then(|handle| heap.index(handle)).is_none() + { + once!(slot, n, "fresh descriptor table exceeds the available span"); + continue; + } // The table and what its entries hold (record words). let key = { use std::hash::{Hash, Hasher}; @@ -1136,33 +2513,41 @@ impl State { // SAFETY: a descriptor slot in title memory. unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h); } - (table, h.finish()) + (table, n, h.finish()) }; if let Some(&first) = self.fresh_tables.get(&key) { for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { let handle = table + u64::from(u.table_offset_dwords) * 4; if let Some(view) = crate::descriptor::view(handle) { - readable(list, u, &view); + readable(list, u.kind, &view); + } + } + for k in selected { + if entries.iter().any(|u| u.table_offset_dwords / 8 == k) { + continue; + } + let handle = table + u64::from(k) * 32; + if let Some(view) = crate::descriptor::view(handle) + && let Some(kind) = view_kind(&view) + { + readable(list, kind, &view); } } made.push((slot, first * 32)); continue; } let Some(first) = host.dynamic(n) else { - // Without its fresh table the shader would read the title's - // slots, which for constant buffer tables hold no constant - // view: a texture or null descriptor read as a buffer gives - // a wild address on AMD and the device is removed (#59). - // The draw or dispatch is dropped instead. - return None; + // No room: the draw must not run with the title's own + // offsets (slots never made for it); `bind` drops it. + made.push((slot, u32::MAX)); + continue; }; self.fresh_tables.insert(key, first); - self.dynamic.push(FreshTable { - key, - heap: std::ptr::from_ref(heap) as usize, - first, - count: n, - }); + self.dynamic + .push((std::ptr::from_ref(heap) as usize, first, n)); + // The title's own slots of this table: what the draw reads of + // them it brings up to date here, in the dynamic slots. + let title_first = heap.index(table).filter(|first| first + n <= host.count()); // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). for k in 0..n { @@ -1178,19 +2563,24 @@ impl State { host.constant_at(index, gpu, size); } Some(view) => { - if let Some((src, len, align, mut desc)) = - crate::descriptor::host::unaligned_srv(&view) + host.make_at(index, &view); + let kind = used.map(|u| u.kind).or_else(|| { + selected.binary_search(&k).ok().and_then(|_| view_kind(&view)) + }); + if let Some(kind) = kind { + readable(list, kind, &view); + } + // The title's slot is a table's: out of the queue + // of textures picked by index if the draw read it + // (its texture is up to date now), and made in + // place as the texture pass would have made it, + // for a shader that picks it by index all the same. + if let Some(title) = title_first + && crate::descriptor::host::is_texture_view(&view) { - if let Some((buf, at)) = list.aligned_copy(src, len, align) { - desc.Anonymous.Buffer.FirstElement = at / align; - host.srv_at(index, &buf, &desc); - } else { - host.make_null(index); - } - } else { - host.make_at(index, &view); - if let Some(u) = used { - readable(list, u, &view); + host.texture_slot_tabled(title + k, kind.is_some()); + if kind.is_some() { + host.mirror(title + k, table + u64::from(k) * 32, true); } } } @@ -1204,13 +2594,7 @@ impl State { } made.push((slot, first * 32)); } - Some(made) - } - - fn release_rejected_tables(&mut self, reserved_before_bind: usize) { - for table in self.dynamic.drain(reserved_before_bind..) { - self.fresh_tables.remove(&table.key); - } + made } /// The first draws, at debug level: what they bind and read @@ -1226,7 +2610,7 @@ impl State { let targets: Vec = self .targets .iter() - .filter_map(|&t| crate::resource::host_resource(t as This)) + .filter_map(|&t| crate::resource::host_made(t as This)) .map(|t| { // SAFETY: a live resource. let d = unsafe { t.GetDesc() }; @@ -1287,10 +2671,14 @@ impl State { first: u32, first_instance: u32, ) { + self.window = None; #[cfg(feature = "diagnostics")] self.trace("draw", vertices, first); - let rects = self.topology == RECTANGLES; - let ran = self.prepare(list, false) && (!rects || self.rectangles(list, vertices, first)); + let ready = self.prepare(list, false); + // A pipeline with the rectangle geometry stage draws the title's + // vertices as they are; any other gets its rectangles expanded. + let rects = self.topology == RECTANGLES && !self.completes_rects(); + let ran = ready && (!rects || self.rectangles(list, vertices, first)); if ran { // Rectangles were expanded into their own vertex buffers. let (count, from) = if rects { @@ -1300,7 +2688,6 @@ impl State { }; #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false)); - list.flush_barriers(); // SAFETY: an open list with everything set. unsafe { list.list @@ -1315,6 +2702,12 @@ impl State { } } + /// Whether the bound pipeline completes rectangles itself, in the + /// geometry stage rectangle pipelines get (`HostPipeline::rects`). + fn completes_rects(&self) -> bool { + crate::pipeline::host_pipeline(self.pipeline as This).is_some_and(|p| p.rects) + } + /// Binds vertex buffers holding the rectangles of vertices `first..first /// + count` as triangles, made when the list is submitted. fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool { @@ -1349,6 +2742,10 @@ impl State { let (from, to, stride) = (from as usize, to as usize, stride as usize); let n = rects as usize; list.defer_host(move || { + // The vertices are read in place, at submission: no change + // of mapping under the read (see + // `crate::watch::title_memory_reading`). + let _mapped = crate::watch::title_memory_reading(); // SAFETY: the vertices lie in a title buffer (checked when // recorded) and the scratch memory is the list's. let (src, dst) = unsafe { @@ -1379,16 +2776,19 @@ impl State { base: i32, first_instance: u32, ) { + self.window = None; #[cfg(feature = "diagnostics")] self.trace("indexed", indices, first); - if self.topology == RECTANGLES { + // Indexed rectangles are drawn by the rectangle geometry stage + // alone (nothing expands them on the CPU). + let lost = self.topology == RECTANGLES && !self.completes_rects(); + if lost { once!("indexed rectangles not drawn"); } - let ran = self.topology != RECTANGLES && self.prepare(list, true); + let ran = !lost && self.prepare(list, true); if ran { #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false)); - list.flush_barriers(); // SAFETY: an open list with everything set. unsafe { list.list @@ -1424,6 +2824,9 @@ impl State { crate::pipeline::note_drop(self.pipeline as This); return false; } + if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() { + return false; + } const DRAW: u32 = 0; const INDEXED: u32 = 1; const DISPATCH: u32 = 2; @@ -1432,22 +2835,48 @@ impl State { let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); #[cfg(not(feature = "diagnostics"))] let why = |_: &str| {}; - // A call whose pipeline is not made yet cannot run. That is common - // while the world builds its pipelines; drop it before refreshing and - // clamping records nothing will read. - if crate::pipeline::host_pipeline(self.pipeline as This).is_none() { + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { #[cfg(feature = "diagnostics")] crate::pipeline::note_drop(self.pipeline as This); - why("no host pipeline"); + return false; + }; + // Indirect rectangles (the title's tiled lighting, 256 + // indirect draws a frame, makes their corners from the vertex + // number) are completed by the pipeline's geometry stage: the + // arguments stay the title's, three vertices a rectangle. They + // cannot be expanded on the CPU, which does not know their count. + // shortcut: in a pipeline without that stage, a rectangle with no + // per-vertex inputs is drawn as its first triangle (three vertices, + // half of it), and one with vertex buffers is not drawn. + let made_rects = !p.rects + && kind == DRAW + && self.topology == RECTANGLES + && !p.inputs.iter().any(|e| !e.per_instance); + if made_rects { + once!("indirect rectangles without vertex inputs drawn as their first triangle"); + } + let matches_kind = match kind { + DRAW | INDEXED => { + (self.topology != RECTANGLES || made_rects || p.rects) && !p.compute && !p.mesh + } + MESH => !p.compute && p.mesh, + DISPATCH => p.compute, + _ => false, + }; + if !matches_kind { + why(&format!( + "pipeline mismatch (compute {}, mesh {}, topology {})", + p.compute, p.mesh, self.topology + )); return false; } let len = u64::from(stride) * u64::from(max.max(1)); - let Some(args) = crate::shadow::find(arguments, len) else { + let Some(args) = crate::shadow::find_any(arguments, len) else { why("arguments outside title buffers"); return false; }; let counter = match count { - Some(at) => match crate::shadow::find(at, 4) { + Some(at) => match crate::shadow::find_any(at, 4) { Some(s) => Some((s, at)), None => { why("count outside title buffers"); @@ -1463,68 +2892,125 @@ impl State { why("no host signature"); return false; }; - args.refresh(list, arguments, len); - if let Some((s, at)) = &counter { - s.refresh(list, *at, 4); - } - // The clamp writes the argument shadow as UAV, then leaves it - // in INDIRECT_ARGUMENT for ExecuteIndirect. - crate::list::ensure_shadow_state(list, &args, 0x8); - // Bounded first: the clamp binds a compute pipeline of its own. - if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) { - why("not bounded (no clamp, or arguments not 4-byte aligned)"); + if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) { + why("mesh draws are switched off (VICTORY_MESH_TEST=skip)"); return false; } - list.note_shadow_state(&args, 0x200); - if let Some((shadow, _)) = &counter { - crate::list::ensure_shadow_state(list, shadow, 0x200); - } - self.host_pipeline = 0; - self.host_roots[1] = 0; + // A window of records clamped in one pass (`windows`): for single + // records without a count buffer, drawn by shaders that store to no + // buffer. Anything else ends the window: it uses the scratch buffer + // or may write the arguments. + const WINDOW_USE: usize = usize::MAX - 0x77; + let offset = args.offset(arguments); + let windowed = windows() + && kind != DISPATCH + && max == 1 + && count.is_none() + && !p.stages.iter().any(|stage| stage.translated().stores); + // Another host list (a new one after a cut, or this one after its + // reset) has another scratch buffer, or this one's with old bytes. + if !windowed || list.first_use(WINDOW_USE) { + self.window = None; + } + let same = |w: &Window| w.copy == args.id() && w.kind == kind && w.stride == stride; + let hit = self + .window + .as_ref() + .filter(|w| same(w) && offset >= w.base) + .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records)) + .map(|w| (w.scratch.clone(), offset - w.base)); + let (bounded, at) = match hit { + Some(hit) => hit, + None => { + // A record a short step after the last window's last one + // (the same step as that window's, if it had one): the + // title walks the buffer, so the ones that step apart + // after it are clamped with it. + let (step, records) = match &self.window { + Some(w) if windowed && same(w) => { + let last = w.base + u64::from(w.records - 1) * u64::from(w.step); + let step = offset.saturating_sub(last); + let walks = step >= u64::from(stride) + && step <= 256 + && step % 4 == 0 + && (w.records == 1 || step == u64::from(w.step)); + if walks { + let fit = (args.left(arguments) / step).min(WINDOW_MOST) as u32; + (step as u32, (if w.records == 1 { 16 } else { w.records * 2 }).min(fit).max(1)) + } else { + (stride, max) + } + } + _ => (stride, max), + }; + args.refresh(list, arguments, len.max(u64::from(step) * u64::from(records))); + if let Some((s, at)) = &counter { + s.refresh(list, *at, 4); + } + // Bounded first: the clamp binds a compute pipeline of its + // own and copies clamped active records into a scratch + // buffer at offset 0. + let count_arg = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); + // More than the record asked for: a window clamped ahead, + // whose unfilled slots must not spend the list's budget. + let bounded = if windowed && records > 1 { + crate::indirect::bound_ahead(list, (&args.buffer, offset), (kind, step, records)) + } else { + crate::indirect::bound(list, (&args.buffer, offset), count_arg, (kind, step, records)) + }; + let Some(bounded) = bounded else { + self.window = None; + why("not bounded (no clamp, or arguments not 4-byte aligned)"); + return false; + }; + self.host_pipeline = 0; + self.host_roots[1] = 0; + self.window = windowed.then(|| Window { + copy: args.id(), + kind, + stride, + step, + base: offset, + records, + scratch: bounded.clone(), + }); + (bounded, 0) + } + }; let ran = match kind { - DRAW | INDEXED => self.topology != RECTANGLES && self.prepare(list, kind == INDEXED), + DRAW | INDEXED => self.prepare(list, kind == INDEXED), MESH => self.prepare_for(list, false, true), - DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) { - Some(p) if p.compute => self.bind(list, p, true), - _ => false, - }, + DISPATCH => self.bind(list, p, true), _ => false, }; if !ran { - crate::indirect::done(list, &args.buffer); - list.note_shadow_state(&args, 0x8); - #[cfg(feature = "diagnostics")] - match crate::pipeline::host_pipeline(self.pipeline as This) { - None => crate::pipeline::note_drop(self.pipeline as This), - Some(p) => why(&format!( - "prepare failed (compute {}, mesh {})", - p.compute, p.mesh - )), - } + crate::indirect::done(list, &bounded); + why("prepare failed"); return false; } #[cfg(feature = "diagnostics")] list.note_op(|| { - self.op_text( - format!("indirect kind {kind} max {max} at {arguments:#x}"), - kind == DISPATCH, - ) + self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) }); - list.flush_barriers(); - // SAFETY: an open list with everything set; the buffers are host - // copies the list keeps alive (refresh), the signature is cached. + if kind == MESH { + self.mesh_scissor(list, true); + } + // SAFETY: an open list with everything set; the scratch buffer and + // host copies are kept alive by the list, and the signature is cached. unsafe { list.list.ExecuteIndirect( &signature, max, - &args.buffer, - args.offset(arguments), + &bounded, + at, counter.as_ref().map(|(s, _)| &s.buffer), counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) }; - crate::indirect::done(list, &args.buffer); - list.note_shadow_state(&args, 0x8); + if kind == MESH { + self.mesh_scissor(list, false); + } + crate::indirect::done(list, &bounded); if kind == DISPATCH { DISPATCHED.fetch_add(1, Ordering::Relaxed); } else { @@ -1574,44 +3060,89 @@ fn host_signature(kind: u32, stride: u32) -> Option { /// Gets what a shader reads or writes through a view ready: buffer data /// copied, textures moved to the state they need. -fn readable(list: &HostList, u: &UsedResource, view: &View) { - const SHADER_RESOURCE: u32 = 0x40 | 0x80; +fn view_kind(view: &View) -> Option { + match view { + View::Shader(..) | View::Placed(false, ..) => Some(ResourceType::Srv), + View::Unordered(..) | View::Placed(true, ..) => Some(ResourceType::Uav), + _ => None, + } +} + +/// The host state a depth view needs of its texture: the read state if the +/// view writes no plane the format has (the title's read-only flags), else +/// the write state. +/// shortcut: whole textures have one state, so a view that writes one of +/// two planes counts as writing. +fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>) -> u32 { + // D16_UNORM and D32_FLOAT: depth formats without a stencil plane. + const ONE_PLANE: [i32; 2] = [55, 40]; + let Some(desc) = desc else { + return DEPTH_WRITE; + }; + let format = if desc.Format.0 == 0 { + // SAFETY: a live texture; a view without a format has its own. + unsafe { texture.GetDesc() }.Format.0 + } else { + desc.Format.0 + }; + let mut needed = D3D12_DSV_FLAG_READ_ONLY_DEPTH.0; + if !ONE_PLANE.contains(&format) { + needed |= D3D12_DSV_FLAG_READ_ONLY_STENCIL.0; + } + if desc.Flags.0 & needed == needed { + DEPTH_READ + } else { + DEPTH_WRITE + } +} + +fn readable(list: &HostList, kind: ResourceType, view: &View) { const UNORDERED_ACCESS: u32 = 0x8; let placed = crate::descriptor::host::placed_texture(view); let view = placed.as_ref().unwrap_or(view); // Buffer views read title memory: their range is copied at submission; // what shaders write through unordered access goes back to it after. - let range = match view { - View::Constant(address, size) => Some((*address, u64::from(*size))), - _ => crate::descriptor::host::buffer_range(view), - }; - if let Some((address, len)) = range - && len > 0 - && let Some(shadow) = crate::shadow::find(address, len) - { - let state = match u.kind { - ResourceType::Cbv => 0x1, - ResourceType::Srv => SHADER_RESOURCE, - ResourceType::Uav => UNORDERED_ACCESS, - ResourceType::Other(_) | ResourceType::Sampler => 0, - }; - if state != 0 { - crate::list::ensure_shadow_state(list, &shadow, state); - } + if let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(view) { shadow.refresh(list, address, len); - if u.kind == ResourceType::Uav { - shadow.gpu_writes(list, address, len); + if kind == ResourceType::Uav { + // A shader that cannot store to buffers leaves the range as + // the title has it: nothing to find afterwards. + if STORES.get() || !write_skip() { + shadow.gpu_writes(list, address, len); + } else { + #[cfg(feature = "diagnostics")] + { + crate::copystat::add(crate::copystat::C::GpuWritesLeftOut, 1); + crate::copystat::add(crate::copystat::C::GpuWritesLeftOutBytes, len); + } + } } } - match (view, u.kind) { + match (view, kind) { (View::Shader(resource, _), ResourceType::Srv) => { - if let Some(t) = crate::resource::host_resource(*resource as This) - && (crate::texture::title_written(t) - || crate::texture::recheck_due(*resource as This, crate::queue::presented())) + // A view the title placed, in another format, in the memory of + // a texture the host writes: that texture's texels, copied on + // the host (title memory does not have them). + let aliased = crate::resource::alias_of(*resource as This) + .is_some_and(|source| crate::texture::alias(list, *resource as This, source)); + if !aliased + && let Some(t) = crate::resource::host_resource(*resource as This) + && crate::texture::title_written(t) { crate::texture::upload(list, *resource as This, t); } - crate::list::ensure_state(list, *resource as This, SHADER_RESOURCE); + // A depth texture shaders also write: what they wrote, first. + list.twin_use(*resource as This, false, false); + // The depth target the draw only tests is read in both ways at + // once: both read states, which its preparation asks for too. + let (tested, _) = TESTED_DEPTH.get(); + let state = if tested != 0 && tested == *resource { + TESTED_DEPTH.set((tested, true)); + DEPTH_READ | SHADER_RESOURCE + } else { + SHADER_RESOURCE + }; + crate::list::ensure_state(list, *resource as This, state); #[cfg(feature = "diagnostics")] if let Some(t) = crate::resource::host_resource(*resource as This) { // SAFETY: a live resource. @@ -1628,34 +3159,139 @@ fn readable(list: &HostList, u: &UsedResource, view: &View) { (View::Unordered(resource, _, _), ResourceType::Uav) => { #[cfg(feature = "diagnostics")] crate::capture::note_target(*resource as This); - crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS); + // Unordered access to a depth texture is its colour twin's. + if !list.twin_use(*resource as This, true, true) { + crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS); + } } _ => {} } } +/// The pixel shaders whose draws get their slots listed +/// ([`State::slots_text`]): `VICTORY_LIST_SLOTS`, hash prefixes separated +/// by commas. None by default. +#[cfg(feature = "diagnostics")] +fn list_slots() -> &'static [String] { + static LIST: std::sync::OnceLock> = std::sync::OnceLock::new(); + LIST.get_or_init(|| { + std::env::var("VICTORY_LIST_SLOTS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_ascii_lowercase()) + .filter(|s| !s.is_empty()) + .collect() + }) +} + +/// A fingerprint of the 4 KiB of title memory at `at` (FNV-1a, 64 bits; of +/// 4 KiB of zeros it is always the same value, which `slots.py` knows), or +/// "unreadable". +#[cfg(feature = "diagnostics")] +fn print_4k(at: u64) -> String { + let mut bytes = [0u8; 4096]; + if at == 0 || !crate::host::read_into(at as *const u8, &mut bytes) { + return "unreadable".into(); + } + let mut hash = 0xcbf2_9ce4_8422_2325_u64; + for b in bytes { + hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); + } + format!("{hash:016x}") +} + +/// The `bytes` of title memory at `at`: how many are mapped, and the +/// fingerprints of the first and the last 4 KiB (a texture's smallest +/// levels lie first, its largest last). +#[cfg(feature = "diagnostics")] +fn memory_state(at: u64, bytes: u64) -> String { + let mapped = crate::texture::mapped_bytes(at as *const u8, bytes as usize); + let last = at + bytes.saturating_sub(4096); + format!("memory={at:#x} mapped={mapped}/{bytes} first4k={} last4k={}", print_4k(at), print_4k(last)) +} + +/// Title texture `this` for the frame listing: its size, whether it has a +/// host copy (not made here), its staging buffer's state, whether the host +/// copied into it, and its memory ([`memory_state`]). +#[cfg(feature = "diagnostics")] +fn texture_state(this: This) -> String { + let Some((at, desc)) = crate::resource::texture_memory(this) else { + return "not a texture".into(); + }; + // SAFETY: 56 bytes in the description's layout. + let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() }; + let bytes = crate::resource::placed_bytes(&words).unwrap_or(0); + let staged = match crate::texture::staged_state(this) { + Some((uploaded, dirty)) => format!("staged=yes uploaded={uploaded} dirty={dirty}"), + None => "staged=no".into(), + }; + format!( + "{}x{} f{} levels={} host_copy={} {staged} host_written={} title_fills={} {}", + u64::from(words[4]) | u64::from(words[5]) << 32, + words[6], + words[8], + words[7] >> 16, + crate::resource::host_made(this).is_some(), + crate::texture::host_wrote(this as usize), + crate::resource::title_fills(this), + memory_state(at as u64, bytes) + ) +} + +/// A view of the title's heap for the frame listing: a texture with its +/// state ([`texture_state`]; a placed one that has no resource yet with +/// its memory alone), anything else in a few words. +#[cfg(feature = "diagnostics")] +fn view_state(view: Option<&View>) -> String { + match view { + None => "no view".into(), + Some(View::Placed(false, r, d)) if r[0] != 1 => { + let address = u64::from(d[10]) | u64::from(d[11]) << 32; + let state = match crate::resource::texture_at_made(address, r) { + Some(this) => texture_state(this), + None => format!( + "{}x{} f{} levels={} resource=none {}", + u64::from(r[4]) | u64::from(r[5]) << 32, + r[6], + r[8], + r[7] >> 16, + memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0)) + ), + }; + format!("placed texture view_format={} {state}", d[0]) + } + Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => { + format!( + "texture object {r:#x} view_format={} {}", + d.as_ref().map_or(0, |d| d[0]), + texture_state(*r as This) + ) + } + Some(v) => format!("{v:?}").chars().take(80).collect(), + } +} + /// A view in a few words (diagnostics builds). #[cfg(feature = "diagnostics")] fn describe(view: Option<&View>) -> String { let texture = |r: This| { - crate::resource::host_resource(r).map(|t| { + crate::resource::host_made(r).map(|t| { // SAFETY: a live resource. let d = unsafe { t.GetDesc() }; - format!( - "{}x{} f{} flags {:#x}", - d.Width, d.Height, d.Format.0, d.Flags.0 - ) + format!("{}x{} f{} flags {:#x} of {r:?}", d.Width, d.Height, d.Format.0, d.Flags.0) }) }; match view { None => "no view".into(), Some(v @ View::Shader(r, _)) => texture(*r as This) .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))), - // A buffer has no host texture: its title range, as for a shader view. - Some(v @ View::Unordered(r, ..)) => texture(*r as This).map_or_else( - || format!("uav buffer {:?}", crate::descriptor::host::buffer_range(v)), - |t| format!("uav {t}"), - ), + Some(v @ View::Unordered(r, ..)) => match texture(*r as This) { + Some(t) => format!("uav texture {t}"), + None => format!( + "uav resource {r:#x} buffer {:?}", + crate::descriptor::host::buffer_range(v) + ), + }, Some(View::Placed(u, r, d)) => format!( "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}", r[0], @@ -1701,14 +3337,17 @@ pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) { } pub(crate) fn stencil_ref(list: &HostList, reference: u32) { + #[cfg(feature = "diagnostics")] + crate::capture::op(std::ptr::from_ref(list) as usize, || format!("STENCIL REF {reference:#x}")); // SAFETY: an open list. unsafe { list.list.OMSetStencilRef(reference) }; } -/// The title's depth bounds test range, on hosts that support it (a -/// pipeline with the test enabled draws nothing outside it). pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) { - use windows::core::Interface; + #[cfg(feature = "diagnostics")] + crate::capture::op(std::ptr::from_ref(list) as usize, || { + format!("DEPTH BOUNDS {min}..{max}") + }); if crate::host::host().is_some_and(|h| h.depth_bounds()) && let Ok(l1) = list.list.cast::() { @@ -1716,152 +3355,3 @@ pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) { unsafe { l1.OMSetDepthBounds(min, max) }; } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::descriptor::{heap, test_view_heap}; - use crate::pipeline::{Shader, Translated}; - use victory_shader::{HwStage, emit::HostShader}; - use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; - use windows::Win32::Graphics::Direct3D::ID3DBlob; - use windows::core::s; - - #[test] - fn rejected_bind_releases_only_its_new_tables() { - let Some(host) = crate::host::host() else { - return; - }; - let list = host.new_list().unwrap(); - let source = b"[numthreads(1,1,1)] void main() {}"; - let mut code: Option = None; - // SAFETY: the source is live and the out pointer is valid. - unsafe { - D3DCompile( - source.as_ptr().cast(), - source.len(), - s!("test"), - None, - None, - s!("main"), - s!("cs_5_1"), - 0, - 0, - &mut code, - None, - ) - } - .unwrap(); - let code = code.unwrap(); - // SAFETY: the blob owns the returned byte range. - let dxil = unsafe { - std::slice::from_raw_parts(code.GetBufferPointer().cast(), code.GetBufferSize()) - } - .to_vec(); - let used = [2, 4, 3] - .into_iter() - .enumerate() - .map(|(slot, size)| UsedResource { - kind: ResourceType::Cbv, - root: RootType::Table, - table_offset_dwords: (size - 1) * 8, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 0, - slot: slot as u8, - }) - .collect(); - let shader = Shader::test_compute(Translated { - host: HostShader { - stage: HwStage::Cs, - dxil, - user_data: Vec::new(), - samplers: Vec::new(), - static_samplers: Vec::new(), - root_cbvs: Vec::new(), - root_srvs: Vec::new(), - address_map: false, - descriptor_words: false, - root_uavs: Vec::new(), - root_indexed_views: Vec::new(), - mesh_emu: None, - }, - used, - }); - let pipeline = HostPipeline::new(&[shader], None).unwrap(); - let title_heap = test_view_heap(9); - let guest = heap(title_heap); - let view_heap = guest.host().unwrap(); - // SAFETY: a live heap. - // The heap itself runs past them to the null slot view indices clamp to. - let capacity = view_heap.dynamic_slots(); - - let mut state = State::default(); - state.heaps[0] = title_heap as usize; - state.set_table(true, 0, guest.start); - assert!(state.bind(&list, &pipeline, true)); - assert_eq!(state.dynamic.len(), 1); - let (&accepted_key, &accepted_first) = state.fresh_tables.iter().next().unwrap(); - - // Leave six slots after the accepted two-slot table. A four-slot - // table fits but the following three-slot table cannot fit. - let blocker = view_heap.dynamic(capacity - 8).unwrap(); - state.set_table(true, 1, guest.start + 2 * 32); - state.set_table(true, 2, guest.start + 6 * 32); - assert!(!state.bind(&list, &pipeline, true)); - assert_eq!(state.dynamic.len(), 1); - assert_eq!(state.fresh_tables.len(), 1); - assert_eq!(state.fresh_tables[&accepted_key], accepted_first); - - // Check both free ranges independently because the upstream scan - // splits a run at its cursor (issue #871). - let tail = view_heap.dynamic(2).unwrap(); - let returned = view_heap.dynamic(4).unwrap(); - assert_eq!(returned + 4, tail); - assert!(view_heap.dynamic(1).is_none()); - view_heap.release(tail, 2); - view_heap.release(returned, 4); - view_heap.release(blocker, capacity - 8); - - assert!(state.bind(&list, &pipeline, true)); - assert_eq!(state.dynamic.len(), 3); - assert_eq!(state.fresh_tables[&accepted_key], accepted_first); - drop(state); - crate::object::slot:: u32>(title_heap, 0x10)(title_heap); - } -} - -#[cfg(all(test, feature = "diagnostics"))] -mod breadcrumb_tests { - use super::*; - use victory_shader::emit::UserData; - - #[test] - fn breadcrumbs_distinguish_constants_rebuilt_tables_and_missing_tables() { - let mut state = State::default(); - state.set_table(false, 1, 0x1000); - let bound = BoundUserData { - values: vec![0x1234, 0x8000, 0], - rebuilt_tables: vec![(1, 0x8000)], - }; - let mut text = String::new(); - for (index, root) in [ - (0, RootType::Constants), - (1, RootType::Table), - (2, RootType::Table), - ] { - let data = UserData { - index, - slot: index as u8, - root, - dword: 0, - }; - state.note_user_data(&mut text, false, &data, &bound); - } - assert_eq!( - text, - " u0=0x1234 u1=0x8000 [rebuilt view table base 1024] u2=0x0 [unbound table]" - ); - } -} diff --git a/crates/victory-gpu/src/dxgi.rs b/crates/victory-gpu/src/dxgi.rs index c7f7c45..af10227 100644 --- a/crates/victory-gpu/src/dxgi.rs +++ b/crates/victory-gpu/src/dxgi.rs @@ -219,7 +219,28 @@ struct Mode { } const _: () = assert!(size_of::() == 32); -/// The console's mode list: one 4K mode at 60 Hz (Grand Theft Auto VI looks +/// The size of the display the console reports: `VICTORY_DISPLAY_MODE=WxH` +/// if set (as a console reports the television it is plugged into: a +/// Series X on a 1080p set lists a 1080p mode), else 3840x2160. +/// shortcut: not yet the host display's own size by default; make it so +/// once a title is seen to render for the mode it is given. +fn display_size() -> (u32, u32) { + static SIZE: std::sync::OnceLock<(u32, u32)> = std::sync::OnceLock::new(); + *SIZE.get_or_init(|| { + let asked = std::env::var("VICTORY_DISPLAY_MODE").ok().and_then(|v| { + let (w, h) = v.trim().split_once(['x', 'X'])?; + Some((w.trim().parse::().ok()?, h.trim().parse::().ok()?)) + }); + let size = match asked { + Some((w, h)) if (640..=7680).contains(&w) && (360..=4320).contains(&h) => (w, h), + _ => (3840, 2160), + }; + tracing::info!(width = size.0, height = size.1, "display mode reported to the title"); + size + }) +} + +/// The console's mode list: one 4K mode at 60 Hz (the title looks /// for a 120 Hz one to allow 120 Hz frame intervals). /// shortcut: fixed mode, not the host display's; report the host's rates if /// a title paces by them. @@ -242,9 +263,10 @@ extern "system" fn modes( return MORE_DATA; } *count = 1; + let (width, height) = display_size(); let mode = Mode { - width: 3840, - height: 2160, + width, + height, refresh: [60, 1], format: 0, scanlines: 1, // progressive diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 19509bb..98daa89 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -75,7 +75,7 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT extern "system" fn release(this: This) -> u32 { object::release_boxed::(this) } -extern "system" fn completed(this: This) -> u64 { +pub(crate) extern "system" fn completed(this: This) -> u64 { fence(this).value.load(Ordering::Acquire) } extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT { @@ -88,6 +88,19 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c return S_OK; } if event.is_null() { + // With submissions sent to the card and not waited for + // (`crate::host::late`) the signal may be behind them: they are + // settled, which sets it. + #[cfg(windows)] + if crate::host::late() { + drop(waiters); + crate::host::settle_for_fence(); + if fence.value.load(Ordering::Acquire) >= value { + return S_OK; + } + tracing::warn!(value, "blocking fence wait not implemented"); + return E_NOTIMPL; + } // shortcut: a null event means "block until reached"; nothing can // reach it while no GPU work runs, so fail instead of hanging. tracing::warn!(value, "blocking fence wait not implemented"); @@ -96,7 +109,8 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c waiters.push((value, event as usize)); S_OK } -pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { +/// Moves the fence to `value` and sets the events that waited for it. +pub(crate) fn set(this: This, value: u64) { let fence = fence(this); let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); fence.value.store(value, Ordering::Release); @@ -107,6 +121,12 @@ pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { } !reached }); +} +pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { + set(this, value); + // A queue may have waited for it: what it held runs now. + #[cfg(windows)] + crate::queue::release_held(false); S_OK } @@ -135,9 +155,7 @@ static FUNCTIONS: Table<24> = { #[cfg(test)] mod tests { - #[cfg(windows)] use super::*; - #[cfg(windows)] use crate::object::slot; #[cfg(windows)] @@ -164,7 +182,7 @@ mod tests { // SAFETY: as above. assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL); - // Grand Theft Auto VI reads the value at the fence's address. + // The title reads the value at the fence's address. let at = slot:: u64>(f, 0x60)(f); // SAFETY: the fence's value. assert_eq!(unsafe { *(at as *const u64) }, 5); diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 837dfbc..798b760 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -2,7 +2,7 @@ //! to begin. Ours is a clock started by the first interval set, ticking //! once per interval; the token is the frame number. Each event kind //! (origin, vblank, flip) happens once per tick, so two waits for the same -//! kind never end on the same tick: Grand Theft Auto VI polls the origin +//! kind never end on the same tick: the title polls the origin //! with "token on time-out" (starting its next frame at once) and is paced //! by a blocking wait for the flip before each present. //! @@ -126,8 +126,22 @@ pub(crate) extern "system" fn wait( token: *mut u64, ) -> HRESULT { let origin = kind == ORIGIN; - let (tick, wait) = next_tick(kind); + let (mut tick, mut wait) = next_tick(kind); let limit = Duration::from_millis(u64::from(timeout_ms)); + // A blocking wait for an event that has happened since the last wait + // for it ended (a frame took longer than a tick) ends at once, on the + // tick that passed: sleeping on to the next one cost 17 ms of every + // 730 ms frame (run 58: "2.0 frame waits sleeping 16.8 ms"). Polls (a + // time-out shorter than a tick) answer as before. + // `VICTORY_LATE_WAITS=1` sleeps to the next tick, as before. + static SLEEP: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*SLEEP.get_or_init(|| std::env::var_os("VICTORY_LATE_WAITS").is_some_and(|v| v == "1")) + && limit >= wait + && tick > last(kind).load(Ordering::Relaxed) + 1 + { + tick -= 1; + wait = Duration::ZERO; + } let hr = if wait > limit { std::thread::sleep(limit); TIMEOUT @@ -136,6 +150,12 @@ pub(crate) extern "system" fn wait( last(kind).fetch_max(tick, Ordering::Relaxed); S_OK }; + #[cfg(all(windows, feature = "diagnostics"))] + { + use crate::copystat::{C, add}; + add(C::PaceWaits, 1); + add(C::PaceUs, wait.min(limit).as_micros() as u64); + } // 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. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index c6dbbd8..492ae72 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1,10 +1,11 @@ //! The host GPU: one D3D12 device and direct queue (decision 0007), and a //! window to present on. //! -//! shortcut: every submission is waited for, so CPU and GPU never overlap; +//! shortcut: every submission is waited for, so CPU and GPU never overlap +//! (unless `VICTORY_LATE_WAIT=1`, see [`late`]); //! overlap them with per-submission fences once more than clears run. -use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Mutex, OnceLock}; use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM}; @@ -37,8 +38,6 @@ const RTV_RING: u32 = 1024; pub(crate) struct Host { pub(crate) device: ID3D12Device, - /// Dedicated video memory of the adapter the device is on, in bytes. - memory: u64, queue: ID3D12CommandQueue, fence: ID3D12Fence, /// The last value signalled on `fence`, behind the submission lock. @@ -55,6 +54,9 @@ pub(crate) struct Host { messages: Option, next_rtv: AtomicU32, presenter: Mutex>, + /// The adapter the device is on, for its memory budget + /// ([`Host::video_memory`]); `None` if the system does not name it. + adapter: Option, } // SAFETY: D3D12 devices, queues, fences and descriptor heaps are @@ -63,21 +65,385 @@ unsafe impl Send for Host {} // SAFETY: as above. unsafe impl Sync for Host {} +/// Host objects the title let go of while a submission may still use them +/// (a texture its descriptors name, a descriptor slot's old resource), by +/// the submission count they wait for. The title's descriptor writes and +/// releases reach the host at once, from its own threads, while the host +/// runs a submission: freeing there is a GPU page fault on the freed +/// texture (a device hang). +static RETIRED: Mutex> = Mutex::new(Vec::new()); +/// Submissions started and finished (waited for). +static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A retired object, dropped on whatever thread finishes the submission. +struct Retired(#[allow(dead_code)] Box); +// SAFETY: what is retired is D3D12 objects (free-threaded) and the +// reference-counted wrappers holding them, dropped once. +unsafe impl Send for Retired {} + +/// Milliseconds since the first call. +pub(crate) fn now_ms() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +/// This moment, for telling later how long ago it was ([`long_ago`]): the +/// frames begun so far (high half, `crate::frame::current`) and tenths of a +/// second since the start. Host copies of title memory, staging buffers and +/// host textures note when they were last used with it. +pub(crate) fn moment() -> u64 { + (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff) +} + +/// Whether `moment` lies at least `ms` milliseconds and `frames` frames +/// back. Both: at seconds per frame, what every frame uses is not touched +/// for seconds, and at many frames per second not for many frames. (A title +/// that never waits for frames has no frame count: nothing is then idle.) +pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool { + let now = self::moment(); + let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff); + (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms +} + +/// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`. +pub(crate) fn available_physical_ram() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + // SAFETY: a sized structure. + let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0; + ok.then_some(m.ullAvailPhys) +} + +/// Effective idle timeout (in milliseconds) for VRAM-backed host textures, +/// scaled down under VRAM pressure. Never returns less than 1,000 ms so +/// handles not yet recorded into a list or slot remain protected. +pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 { + const NORMAL_MS: u64 = 5_000; + const MODERATE_MS: u64 = 2_500; + const HIGH_MS: u64 = 1_000; + let Some([budget, used, ..]) = video_memory else { + return NORMAL_MS; + }; + if budget == 0 { + return NORMAL_MS; + } + let used_pct = (u128::from(used) * 100) / u128::from(budget); + if used_pct >= 85 { + HIGH_MS + } else if used_pct >= 75 { + MODERATE_MS + } else { + NORMAL_MS + } +} + +/// Effective idle timeout (in milliseconds) for system-RAM caches (staging +/// buffers, loose shadows, and the mapped pipeline library), scaled down +/// when free physical RAM is low. Never returns less than 2,000 ms. +pub(crate) fn ram_idle_ms(avail_phys: Option) -> u64 { + const GIB: u64 = 1024 * 1024 * 1024; + const NORMAL_MS: u64 = 10_000; + const MODERATE_MS: u64 = 5_000; + const HIGH_MS: u64 = 2_000; + let Some(avail) = avail_phys else { + return NORMAL_MS; + }; + if avail < 2 * GIB { + HIGH_MS + } else if avail < 4 * GIB { + MODERATE_MS + } else { + NORMAL_MS + } +} + +/// How many references are held on a host object (its COM count): ours +/// all, since the host's views and commands hold none. A buffer or texture +/// with one is held by its owner alone: no descriptor slot keeps it +/// (`HostHeap::kept`) and no list (`HostList::keep`). +pub(crate) fn references(object: &impl Interface) -> u32 { + type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32; + let raw = object.as_raw(); + // SAFETY: a live COM object, whose first three methods are those of + // `IUnknown` (query, add a reference, release one); the pair leaves the + // count as it was, and the release returns it. The first is not called. + unsafe { + let methods = *raw.cast::<*const [Method; 3]>(); + ((*methods)[1])(raw); + ((*methods)[2])(raw) + } +} + +/// Once a second, before a submission starts: lets go of what nothing +/// names any more (copies of windows of title memory, staging buffers, +/// host copies of textures the title fills). +/// `VICTORY_SWEEP=0` keeps everything, as before. +fn sweep() { + // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`). + crate::inplace::tick(); + static ON: OnceLock = OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) { + return; + } + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let now = now_ms(); + let last = LAST.load(Ordering::Relaxed); + if now < last + 1000 + || LAST + .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed) + .is_err() + { + return; + } + crate::pipeline::trim_library(); + crate::shadow::let_go_idle(); + crate::texture::let_go_idle(); + crate::resource::let_go_idle(); +} + +/// Drops `object` once every submission running now has finished: at once +/// if none is. +pub(crate) fn retire(object: T) { + let started = STARTED.load(Ordering::Acquire); + if started <= FINISHED.load(Ordering::Acquire) { + RETIREMENTS[0].fetch_add(1, Ordering::Relaxed); + drop(object); + return; + } + RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); + RETIRED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((started, Retired(Box::new(object)))); +} + +/// Drops what waited for submissions up to `finished`. +fn bury(finished: u64) { + let done: Vec<(u64, Retired)> = { + let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); + if retired.is_empty() { + return; + } + let (done, keep) = std::mem::take(&mut *retired) + .into_iter() + .partition(|(at, _)| *at <= finished); + *retired = keep; + done + }; + drop(done); +} + +/// Objects [`retire`] dropped at once (no submission was running) and +/// kept until a running submission finished, since the start. +static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// What the layer did to the host's objects lately, newest last (sweeps +/// that let host copies go, pipeline library calls, saves and trims): said +/// once when the host device is removed ([`log_removal_context`]), with +/// what the submitting thread and the pipeline workers were doing at that +/// moment. A device the driver removes "internally" names no command, and +/// the pass that happens to notice first names only the view it was at: +/// the three such losses of runs 72, 73 and 82 each came within 5 ms of a +/// pipeline library call that no line of the log tied to them. +/// `VICTORY_TRAIL=0`: nothing is kept and nothing is said. +static TRAIL: Mutex> = Mutex::new(std::collections::VecDeque::new()); +/// The entries kept. +const TRAIL_MOST: usize = 96; + +fn trail_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0")) +} + +/// Microseconds since the first call. +pub(crate) fn now_us() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 +} + +/// The calling thread, as the log's other lines name threads. +pub(crate) fn thread_id() -> u32 { + // SAFETY: a plain query. + unsafe { windows::Win32::System::Threading::GetCurrentThreadId() } +} + +/// Notes something done to the host's objects ([`TRAIL`]); `what` is only +/// run when the trail is kept. +pub(crate) fn trail(what: impl FnOnce() -> String) { + if !trail_on() { + return; + } + let entry = (now_us(), thread_id(), what()); + let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner()); + if trail.len() >= TRAIL_MOST { + trail.pop_front(); + } + trail.push_back(entry); +} + +/// What the submitting thread is doing (0 nothing: between submissions, +/// 1 preparing one, 2 waiting for the card to run it, 3 copying back what +/// it wrote), the lists of that submission, and since when ([`now_us`]). +static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +fn submitting(phase: u64, lists: usize) { + SUBMITTING[1].store(lists as u64, Ordering::Relaxed); + SUBMITTING[2].store(now_us(), Ordering::Relaxed); + SUBMITTING[0].store(phase, Ordering::Relaxed); +} + +/// What was going on when the host device went: whether a submission was +/// on the card, the pipeline library's state and the calls running in it, +/// and the trail. +pub(crate) fn removal_context() -> String { + use std::fmt::Write; + let now = now_us(); + let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0; + let phase = match SUBMITTING[0].load(Ordering::Relaxed) { + 0 => "between submissions (nothing of ours was running on the card)", + 1 => "preparing a submission (nothing of ours was running on the card)", + 2 => "waiting for the card to run a submission", + _ => "copying back what a submission wrote (nothing of ours was running on the card)", + }; + let mut text = format!( + "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}", + SUBMITTING[1].load(Ordering::Relaxed), + ms(SUBMITTING[2].load(Ordering::Relaxed)), + crate::pipeline::library_removal_note(), + RETIREMENTS[0].load(Ordering::Relaxed), + RETIREMENTS[1].load(Ordering::Relaxed), + STARTED.load(Ordering::Relaxed), + FINISHED.load(Ordering::Relaxed), + ); + let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner()); + let _ = write!(text, "; the last {} things done, newest last:", trail.len()); + for (at, thread, what) in trail.iter() { + let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at)); + } + text +} + +/// Says [`removal_context`] in the log, once: called by whoever finds the +/// host device removed. +pub(crate) fn log_removal_context() { + static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !trail_on() || SAID.swap(true, Ordering::Relaxed) { + return; + } + tracing::error!("when the host device went: {}", removal_context()); +} + /// Time spent in submissions since the last frame-rate line, in /// microseconds: preparing them on the CPU (title memory copies, texture /// detiling), then waiting for the GPU. -static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = [ - std::sync::atomic::AtomicU64::new(0), - std::sync::atomic::AtomicU64::new(0), -]; +static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = + [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; /// After submissions: shader-written ranges compared and copied back into /// title memory (microseconds, bytes that differed), since the last /// frame-rate line. -static COPY_BACK: [std::sync::atomic::AtomicU64; 2] = [ - std::sync::atomic::AtomicU64::new(0), - std::sync::atomic::AtomicU64::new(0), -]; +static COPY_BACK: [std::sync::atomic::AtomicU64; 2] = + [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; + +/// The card's clock, for the frame line of every run, in microseconds since +/// the last one: how long the card had nothing of ours queued; how much of +/// that while the thread that holds the submission lock was working (the +/// card idle behind us: preparing and copying back are done with the card +/// standing); and how long that thread stood waiting for the card. +/// +/// Every send of lists to the queue is followed by a signal on a fence of +/// the clock's own ([`Host::card_sent`]). A thread of the clock waits for +/// the newest signal and notes the moment the card reached it with nothing +/// newer sent; the next send ends that idle stretch. +static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Of the thread that holds the submission lock: the microseconds it has +/// worked so far (preparing, copying back; not its waits for the card), and +/// since when it works now ([`now_us`] plus one; 0: it does not). +static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The thread that holds the submission lock starts (`on`) or stops +/// working; whether it worked until now. +fn working(on: bool) -> bool { + let now = now_us() + 1; + let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed); + if since != 0 { + WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed); + } + since != 0 +} + +/// [`WORKING`] as of now: microseconds worked so far. +fn worked() -> u64 { + let since = WORKING[1].load(Ordering::Relaxed); + let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 }; + WORKING[0].load(Ordering::Relaxed) + now +} + +/// The thread that holds the submission lock stood waiting for the card +/// from `since` until now ([`CARD_CLOCK_US`]). +fn stood(since: std::time::Instant) { + CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed); +} + +/// What [`CARD_CLOCK_US`] is measured with. +struct CardClock { + fence: ID3D12Fence, + /// Signals sent so far; and, while the card has reached the last of + /// them, since when and what [`worked`] said then. + state: Mutex<(u64, Option<(std::time::Instant, u64)>)>, + sent: std::sync::Condvar, +} + +// SAFETY: a fence (free-threaded) behind a lock. +unsafe impl Send for CardClock {} +// SAFETY: as above. +unsafe impl Sync for CardClock {} + +/// The clock's thread: waits for the newest signal sent and notes when the +/// card got there with nothing newer behind it. +fn card_clock_watch(clock: &'static CardClock) { + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + return; + }; + let mut seen = 0; + loop { + let target = { + let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); + while state.0 == seen { + state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner()); + } + state.0 + }; + // SAFETY: the clock's fence and this thread's event. + unsafe { + if clock.fence.SetEventOnCompletion(target, event).is_ok() { + WaitForSingleObject(event, INFINITE); + } + } + seen = target; + let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.0 == target && state.1.is_none() { + state.1 = Some((std::time::Instant::now(), worked())); + } + } +} + +/// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the +/// frame's time. +fn card_clock_line(frames: f64, ms: f64) { + let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + tracing::info!( + "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \ + {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \ + had not submitted; the submitting thread stood waiting for the card {stood:.1} ms", + if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 } + ); +} /// Of the preparing: title memory copies (microseconds, bytes) and texture /// refreshes (microseconds, bytes hashed), since the last frame-rate line. @@ -88,6 +454,48 @@ pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [ std::sync::atomic::AtomicU64::new(0), ]; +/// Host buffers made since the start, as (count, bytes): in the upload heap +/// (staging, list scratch), shared with the processor (host copies of title +/// memory) and the graphics card's own (indirect arguments, twins' copies). +/// For the memory line: against what is alive, they show what was let go. +pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + +/// What of that is alive now, for the memory line (`MADE` counts what was +/// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60, +/// and nothing said how many were alive): host lists; the lists' scratch +/// chunks and their bytes; of those, the chunks no list holds (kept for the +/// next list, [`Spare`]) and their bytes; chunks taken from those kept +/// instead of made, since the start; and the lists' other upload buffers +/// (texture data copied from buffers, scratch too big for a chunk) and +/// their bytes. +pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; + +/// About host lists, for the memory line: lists made by the host since the +/// start; preludes made (a list's second allocator and list, made when it +/// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the +/// bytes the process's private memory grew by while lists were being made +/// (what a list costs: host objects with the driver's command memory; 631 +/// lists were alive in run 65, each with a prelude it may never use). +/// Then the lists alive that were never reset since they were made: the +/// host sides of title lists the title made and has not used (a host list +/// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title +/// makes at its start). +pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// The process's private bytes (diagnostics: around the making of lists). +#[cfg(feature = "diagnostics")] +fn private_bytes() -> 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 +} + /// What the runtime does when the host GPU fails for good: report it like a /// crash and end the run. The console has no such state, and carrying on /// draws nothing at seconds per frame. @@ -107,19 +515,20 @@ pub(crate) fn fail(what: std::fmt::Arguments) -> ! { // SAFETY: a plain query. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } { text.push_str(&format!("; device removed: {e}")); - if let Some(crumbs) = crate::breadcrumb::report() { - text.push_str(&format!("; {crumbs}")); - } + log_removal_context(); } match host.log_messages() { Some(first) => text.push_str(&format!("; debug layer: {first}")), - None if host.messages.is_none() => { - text.push_str("; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command") - } + None if host.messages.is_none() => text.push_str( + "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command", + ), None => {} } } tracing::error!("{text}"); + // Tests have no log: the reason goes to their output. + #[cfg(test)] + eprintln!("host GPU failure: {text}"); match ON_FAILURE.get() { Some(report) => report(&text), None => std::process::abort(), @@ -189,23 +598,39 @@ fn create() -> windows::core::Result { let adapter = warp_adapter()?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); - } else if let Some((adapter, memory, name)) = hardware_adapter() { - match D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device) { - Ok(()) => tracing::info!( - adapter = name, - memory_gb = format_args!("{:.1}", memory as f64 / f64::powi(1024.0, 3)), - "host device on the largest-memory hardware adapter" - ), - Err(e) => { - tracing::warn!(error = %e, adapter = name, "hardware adapter refused D3D12; using the default adapter"); - D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; - } - } } else { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; } let device = device.ok_or_else(windows::core::Error::empty)?; - let memory = adapter_memory(&device); + // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the + // driver compiling shaders again on the "D3D Background Thread"s, + // for minutes after pipelines were made or loaded) is switched off. + // An experiment: while those threads ran, the same shot took + // 1,000-1,200 ms a frame, and 830-950 ms from the moment they + // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default: + // whether the card is slower with the shaders it then keeps is not + // known. + if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0") + && let Ok(device6) = device.cast::() + { + let set = device6.SetBackgroundProcessingMode( + D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK, + D3D12_MEASUREMENTS_ACTION_KEEP_ALL, + None, + None, + ); + tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)"); + } + // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose + // cross-lane code stays in 32-lane halves translated for waves of 32 + let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + if device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32) + .is_ok() + { + tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes"); + victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax); + } let messages = debug .then(|| device.cast::().ok()) .flatten(); @@ -229,10 +654,12 @@ fn create() -> windows::core::Result { ..Default::default() })?; let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); + let adapter = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid())) + .ok(); tracing::info!("host D3D12 device ready"); Ok(Host { device, - memory, queue, fence, submitted: Mutex::new(0), @@ -245,79 +672,11 @@ fn create() -> windows::core::Result { messages, next_rtv: AtomicU32::new(0), presenter: Mutex::new(None), + adapter, }) } } -/// The hardware adapter with the most dedicated video memory, if DXGI knows -/// one: a Ryzen APU plus a discrete card must not default to the APU's small -/// shared-memory device. -fn hardware_adapter() -> Option<(IDXGIAdapter, u64, String)> { - // SAFETY: plain DXGI factory and adapter queries. - unsafe { - let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; - let mut best = None; - for i in 0.. { - let Ok(adapter1) = factory.EnumAdapters1(i) else { - break; - }; - let Ok(desc) = adapter1.GetDesc1() else { - continue; - }; - if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { - continue; - } - let memory = desc.DedicatedVideoMemory as u64; - let end = desc - .Description - .iter() - .position(|&c| c == 0) - .unwrap_or(desc.Description.len()); - let name = String::from_utf16_lossy(&desc.Description[..end]); - let better = best - .as_ref() - .is_none_or(|(_, old, _): &(IDXGIAdapter, u64, String)| memory > *old); - if better { - best = adapter1 - .cast::() - .ok() - .map(|a| (a, memory, name)); - } - } - best - } -} - -/// Dedicated video memory of `device`'s adapter in bytes, zero if DXGI does -/// not say. Matching by LUID also covers a device made on the default adapter. -fn adapter_memory(device: &ID3D12Device) -> u64 { - // SAFETY: plain device and DXGI queries. - unsafe { - let luid = device.GetAdapterLuid(); - let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) else { - return 0; - }; - for i in 0.. { - let Ok(adapter) = factory.EnumAdapters1(i) else { - break; - }; - let Ok(desc) = adapter.GetDesc1() else { - continue; - }; - if desc.AdapterLuid == luid { - return desc.DedicatedVideoMemory as u64; - } - } - 0 - } -} - -/// Dedicated video memory of the host adapter in bytes (`None` without a -/// host device). -pub(crate) fn device_memory() -> Option { - host().map(|h| h.memory) -} - /// 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 { @@ -342,6 +701,41 @@ fn warp_adapter() -> windows::core::Result { #[cfg(test)] mod tests { + #[test] + fn sparse_copies_preserve_islands_and_observe_remaps() { + use windows_sys::Win32::System::Memory::*; + const N: usize = 5 << 16; + // SAFETY: we reserve a private region, commit selected pages inside it, + // and only directly access the pages while they are writable. + unsafe { + let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!base.is_null()); + let mut expected = vec![0; N]; + for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] { + let at = base.add(offset); + assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); + at.write_bytes(value, 4096); + expected[offset..offset + 4096].fill(value); + } + for remap in [false, true] { + if remap { + let mut old = 0; + assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0); + expected[..4096].fill(0); + let at = base.add(1 << 16); + assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); + at.write_bytes(0xc7, 4096); + expected[1 << 16..(1 << 16) + 4096].fill(0xc7); + } + let mut out = vec![0xee; N]; + super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false); + assert_eq!(out[27..N - 27], expected[27..N - 27]); + assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee)); + } + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); + } + } + use super::*; #[test] @@ -386,21 +780,22 @@ pub(crate) struct HostList { /// list names alive until it is reset, even if the title releases the /// resource first. states: Mutex, - /// Shadow buffers and their first/last states in this command list. - shadow_states: Mutex, - /// Texture transition barriers not yet recorded; coalesced and flushed - /// before the next command that may depend on them. - pending_barriers: Mutex>, - /// Whether the list is closed; the console tolerates a repeated close, - /// while host D3D12 fails it with the same E_FAIL as an invalid command. - closed: AtomicBool, - /// The list that runs those transitions just before this one. - prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), + /// What the list does with depth textures that have a colour twin, by + /// twin ([`TwinUse`]). + twins: Mutex>, + /// The list that runs those transitions just before this one, made + /// when the list first has such transitions ([`lazy_prelude`]). + prelude: OnceLock>, /// The pipelines the list binds, for reports of slow submissions. pipelines: Mutex>, /// The work its indirect executions may still do (`indirect`): a /// shader-writable word, zeroed when the list is submitted. budget: OnceLock>, + /// Device-local scratch buffer for clamped indirect arguments (`indirect`), + /// grown to the largest indirect execution recorded on the list. + indirect_args: Mutex>, + /// Counts the list in [`ALIVE`] while it lives. + _alive: Counted, /// 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")] @@ -411,6 +806,20 @@ pub(crate) struct HostList { stamps: OnceLock>, } +/// A list's prelude: an allocator and a closed list. +type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList); + +/// Whether a host list's prelude is made when the list first needs one. A +/// prelude runs the texture transitions and twin copies a list needs before +/// it; lists that name no texture never have one, and every host list was +/// made with one all the same: twice the host objects per list, for the +/// title's 630 lists and for every list made anew. +/// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before. +fn lazy_prelude() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0")) +} + /// Timestamps per list (diagnostics); commands past them are not timed. #[cfg(feature = "diagnostics")] const STAMPS: u32 = 4096; @@ -419,342 +828,3379 @@ const STAMPS: u32 = 4096; #[cfg(feature = "diagnostics")] type Note = (String, Option<(u64, u64)>); -type States = - std::collections::HashMap)>; -type ShadowStates = - std::collections::HashMap)>; +type States = std::collections::HashMap< + usize, + (u32, u32, std::sync::Arc), +>; -/// Whether GPU timestamp diagnostics are enabled (`VICTORY_GPU_TIMING`). -#[cfg(feature = "diagnostics")] -fn timing() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some()) +/// What a list does with a depth texture that has a colour twin +/// ([`crate::resource::Twin`]). Lists are recorded on many threads and run +/// in submission order, so a list cannot know which side an earlier list +/// leaves behind: it notes which sides it uses as it finds them, and its +/// prelude copies one side into the other at submission if that side is +/// behind then. From its first use of a side on, the list knows. +struct TwinUse { + /// The depth texture (the title resource's host copy) and its twin. + depth: std::sync::Arc, + twin: std::sync::Arc, + /// The sides (depth texture, twin) the list uses as it finds them. + needs: [bool; 2], + /// Whether each side lacks what the other was written last, where the + /// list is now; `None`: as the list found it. + behind: [Option; 2], + /// The draw or dispatch being prepared writes the twin. + writing: bool, + /// The depth plane's twin holds what the plane lacks although the list + /// copied the twins since: the plane's pass waits for the list's close. + late: bool, } -/// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics -/// builds). -pub(crate) fn dred_on() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| { - cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some() - }) +/// The pass that draws the twin of a depth plane into the plane: one +/// triangle over each mip of each slice, its pixel shader writing the +/// twin's texel as the depth, with the depth test "always" and no stencil +/// (the stencil plane is copied through a buffer and not touched here). +/// +/// A 16-bit twin holds whole steps of 1/65535, and the depth written is +/// the step times the float nearest 1/65535 (0x37800080). That is how +/// The title's tiled lighting computes the depth of the +/// rectangles it then draws with the test "equal", one class of materials +/// a draw (all six of its vertex shaders multiply the class number by that +/// constant), so the pass and the draw give the host the same float, and +/// the host turns the same float into the same 24 bits. The step divided +/// by 65535 is another float for 512 of the 65,536 steps (none under 257), +/// and lands in another 24-bit step for 127 of them (none under 385). +const PLANE_CORNERS: &str = r#" +float4 corner(uint i : SV_VertexID) : SV_Position { + return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0); } - -/// Names a host object for the device-removed report, which names the -/// allocations a page fault hit (only with device-removed data on). -pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { - if dred_on() - && let Ok(object) = object.cast::() - { - // SAFETY: a plain call on a live object. - let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) }; - } +"#; +const PLANE_STEPS: &str = r#" +#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)" +Texture2DArray twin : register(t0); +[RootSignature(RS)] +float plane(float4 p : SV_Position) : SV_Depth { + return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080); } - -/// Upload chunks handed out front to back: the chunks, the one in use and -/// the bytes used in it. -#[derive(Default)] -struct Scratch { - chunks: Vec<(ID3D12Resource, usize, u64)>, - current: usize, - used: u64, - /// Element-aligned copies of title bytes made for this list, by - /// (source, length, alignment): every draw reading the same view range - /// shares one copy instead of making its own. - copies: std::collections::HashMap<(u64, u64, u64), (ID3D12Resource, u64)>, +"#; +const PLANE_FLOATS: &str = r#" +#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)" +Texture2DArray twin : register(t0); +[RootSignature(RS)] +float plane(float4 p : SV_Position) : SV_Depth { + return twin.Load(int4(int2(p.xy), 0, 0)); } +"#; -// SAFETY: the chunk pointers are persistent mappings of upload buffers. -unsafe impl Send for Scratch {} - -const SCRATCH_CHUNK: u64 = 4 << 20; +/// Views of twins the pass reads, in a heap of ours used as a ring. +/// shortcut: a view must last until its list has run; with one or two +/// passes a frame the ring is far from coming round. +const PLANE_VIEWS: u32 = 256; -/// One piece of submission-time work, in recorded order. -enum Step { - /// A copy into title memory (destination, source, bytes): the title's - /// buffer copies, which later refreshes must see. - Copy(usize, usize, usize), - /// A copy of title memory into the list's own upload memory. - Fill(usize, usize, usize), - /// Brings a range (address, bytes) of a buffer's host copy up to date: - /// once per submission, whichever lists ask, until a `Copy` or `Run` - /// intervenes. - Refresh(std::sync::Arc, usize, usize), - /// Work that may write title memory. - Run(Box), - /// Work that writes host memory only. - Host(Box), - /// Shaders write a range (address, bytes) of a buffer's host copy. - GpuWrite(std::sync::Arc, usize, usize), - /// Brings a texture's staging buffer up to date: once per submission, - /// whichever lists sample it, until a `Copy` or `Run` intervenes. The - /// host copy is uploaded in a prelude when the staging generation changed. - Texture( - std::sync::Arc, - std::sync::Arc, - ), +/// What the pass draws with: the heap of its views of twins, and per kind +/// of twin (16-bit steps or floats) and depth format the root signature +/// and pipeline, made when first needed (`None`: the host refused). +struct PlanePass { + views: ID3D12DescriptorHeap, + cpu: usize, + gpu: u64, + step: u32, + next: AtomicU32, + made: Mutex)>>, } -/// What a list does on the CPU when it is submitted: copies between host -/// memory regions (title buffers, upload buffers and buffer copies), and -/// the upload buffers its GPU commands read, kept until the list is reset. -#[derive(Default)] -struct Deferred { - /// Destination, source, bytes. - copies: Vec, - uploads: Vec, - /// Host objects the list's commands name (pipelines, root signatures, - /// descriptor heaps): the title may release its objects before it - /// submits the list. - kept: Vec, - /// Buffer ranges refreshed since the last title copy (host copy, - /// address, bytes): refreshing them again would find the same bytes. - refreshed: std::collections::HashSet<(usize, usize, usize)>, - /// Textures whose contents the list brings up to date. - textures: std::collections::HashSet, - /// Bottom-of-pipe writes, done once the list has run: address, what, - /// bytes. - writes: Vec<(usize, crate::queue::Written, usize)>, - /// Whether a step zeroes the indirect-work budget. - budget_zeroed: bool, -} +/// The pass's root signature and pipeline for one kind of twin and one +/// depth format. +type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState); -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum MeshSupport { - Native, - Emulate, - Unsupported, +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for PlanePass {} +// SAFETY: as above. +unsafe impl Sync for PlanePass {} + +fn plane_pass() -> Option<&'static PlanePass> { + static PASS: OnceLock> = OnceLock::new(); + PASS.get_or_init(|| { + let host = host()?; + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + // SAFETY: plain heap creation and queries. + unsafe { + let views: ID3D12DescriptorHeap = host + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: PLANE_VIEWS, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + Some(PlanePass { + cpu: views.GetCPUDescriptorHandleForHeapStart().ptr, + gpu: views.GetGPUDescriptorHandleForHeapStart().ptr, + step: host.device.GetDescriptorHandleIncrementSize(kind), + views, + next: AtomicU32::new(0), + made: Mutex::default(), + }) + } + }) + .as_ref() } -impl Host { - fn mesh_support(&self) -> MeshSupport { - static MESH: OnceLock = OnceLock::new(); - *MESH.get_or_init(|| { - let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); - let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { - HighestShaderModel: D3D_SHADER_MODEL_6_6, +/// Compiles function `entry` of `source` for `target` with the system's +/// compiler, as the indirect-argument clamp is (`crate::indirect`). +pub(crate) fn compile( + source: &str, + entry: windows::core::PCSTR, + target: windows::core::PCSTR, +) -> windows::core::Result> { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option = None; + let mut errors: Option = None; + // SAFETY: the source and names live through the call; out pointers ours. + let compiled = unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + windows::core::s!("victory"), + None, + None, + entry, + target, + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + if let Err(e) = compiled { + if let Some(errors) = errors { + // SAFETY: the blob's own bytes. + let text = unsafe { + std::slice::from_raw_parts( + errors.GetBufferPointer().cast::(), + errors.GetBufferSize(), + ) + }; + tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + let code = code.ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob's own bytes. + let bytes = unsafe { + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + }; + Ok(bytes.to_vec()) +} + +impl PlanePass { + /// The root signature and pipeline for a twin of 16-bit steps (`steps`) + /// or of floats and the depth format `format`. + fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) { + return pipeline.clone(); + } + let pipeline = match Self::make(steps, format) { + Ok(pipeline) => Some(pipeline), + Err(e) => { + tracing::warn!( + error = %e, + steps, + format = format.0, + "no pipeline to draw a depth plane from its twin: such planes stay as they are" + ); + None + } + }; + made.push((steps, format.0, pipeline.clone())); + pipeline + } + + fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result { + use windows::core::s; + let device = &host().ok_or_else(windows::core::Error::empty)?.device; + let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?; + let source = if steps { PLANE_STEPS } else { PLANE_FLOATS }; + let ps = compile(source, s!("plane"), s!("ps_5_1"))?; + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + // SAFETY: the root signature is inside the pixel shader; the + // description points at live data and never releases its pointer. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?; + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: code(&vs[..]), + PS: code(&ps[..]), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // Every texel is written; stencil stays off. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + DSVFormat: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?; + Ok((root, pipeline)) + } + } +} + +/// Records into `list` the pass that draws `plane`, the twin of the depth +/// plane of `depth`, into that plane: `depth` in the depth-write state, +/// `plane` readable by pixel shaders. The pass sets the list's descriptor +/// heap, graphics root signature, pipeline, depth target, viewport, +/// scissor and topology and puts none of them back: it is for a list that +/// records nothing of the title's after it. +fn record_plane_pass( + list: &ID3D12GraphicsCommandList, + depth: &ID3D12Resource, + plane: &ID3D12Resource, +) { + let (Some(host), Some(pass)) = (host(), plane_pass()) else { + return; + }; + // SAFETY: live resources. + let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) }; + // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32 + // typeless one floats, read as R32_FLOAT (41). The depth view names + // the depth-stencil format of the texture's family (44: 45, 19: 20). + let steps = twin.Format.0 == 53; + let format = DXGI_FORMAT(match of.Format.0 { + 44 => 45, + 19 => 20, + typed => typed, + }); + let Some((root, pipeline)) = pass.pipeline(steps, format) else { + return; + }; + for slice in 0..u32::from(of.DepthOrArraySize) { + for mip in 0..u32::from(of.MipLevels) { + let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS; + let view = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(if steps { 57 } else { 41 }), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: mip, + MipLevels: 1, + FirstArraySlice: slice, + ArraySize: 1, + ..Default::default() + }, + }, + }; + let target = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: format, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_DSV { + MipSlice: mip, + FirstArraySlice: slice, + ArraySize: 1, + }, + }, + ..Default::default() + }; + let target = host.dsv(depth, Some(&target)); + let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1)); + let cpu = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: pass.cpu + (slot * pass.step) as usize, + }; + let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: pass.gpu + u64::from(slot * pass.step), + }; + // SAFETY: an open list; a slot of our heap; live resources and + // objects (the pass's own live as long as the process). + unsafe { + host.device + .CreateShaderResourceView(plane, Some(&view), cpu); + list.SetDescriptorHeaps(&[Some(pass.views.clone())]); + list.SetGraphicsRootSignature(&root); + list.SetPipelineState(&pipeline); + list.SetGraphicsRootDescriptorTable(0, gpu); + list.OMSetRenderTargets(0, None, false, Some(&target)); + list.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: width as f32, + Height: height as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + list.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }]); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4), + ); + list.DrawInstanced(3, 1, 0, 0); + } + crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed); + } + } +} + +/// Records into `list` the copy of a depth texture into its colour twin +/// (`colour`) or of the twin into the depth texture, both already in their +/// copy states: whole textures of one size in one format family, which the +/// host copies as they are; or, for the twin of a stencil plane, that plane +/// alone, through the twin's buffer. +fn record_twin_copy( + list: &ID3D12GraphicsCommandList, + depth: &ID3D12Resource, + twin: &crate::resource::Twin, + colour: bool, +) { + let (from, to) = if colour { + (depth, &twin.colour.texture) + } else { + (&twin.colour.texture, depth) + }; + crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed); + // shortcut: the depth plane's twin is not given the plane (that is a + // pass the other way: the plane read by a shader, the twin as its + // target). The twin then lacks what draws and clears wrote to the + // plane since shaders last wrote the twin. In the title + // nothing writes that plane but the twin's pass (its 192 draws against + // it only test, run 29), so the twin lacks nothing. Counted. + if colour && twin.plane.is_some() { + crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed); + } + let Some(through) = &twin.through else { + // SAFETY: an open list and two live textures. + unsafe { list.CopyResource(to, from) }; + return; + }; + // A stencil plane and its twin: each mip and slice of the plane goes + // into the buffer, laid out as the host lays the plane out for copies, + // and from the buffer into the other texture, whole subresources both + // times. In the depth texture the stencil plane's subresources follow + // the depth plane's; the twin has the one plane. + let Some(host) = host() else { return }; + // SAFETY: a live texture. + let of = unsafe { depth.GetDesc() }; + let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize); + let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize]; + // SAFETY: a plain query writing `planes` footprints. + unsafe { + host.device.GetCopyableFootprints( + &of, + planes, + planes, + 0, + Some(rows.as_mut_ptr()), + None, + None, + None, + ); + } + let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) }; + let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: index, + }, + }; + let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(through) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: *row, + }, + }; + let (common, source, dest) = ( + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + // SAFETY: an open list and live resources; the buffer was made as big + // as these footprints, and rests in the common state between copies. + unsafe { + list.ResourceBarrier(&[transition(through, common, dest)]); + for (i, row) in rows.iter().enumerate() { + let index = first_from + i as u32; + list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None); + } + list.ResourceBarrier(&[transition(through, dest, source)]); + for (i, row) in rows.iter().enumerate() { + let index = first_to + i as u32; + list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None); + } + list.ResourceBarrier(&[transition(through, source, common)]); + } +} + +/// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics +/// builds). +pub(crate) fn dred_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some() + }) +} + +/// Indirect mesh dispatches since the last frame line: the largest group +/// count a record asked for, and the groups asked in all (from the lists' +/// budget buffers, a run late). +static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether each list of a submission runs and is timed on its own, slow +/// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics +/// builds; the commands are noted with `VICTORY_D3D12_DRED` on). +#[cfg(feature = "diagnostics")] +fn timing() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some()) +} + +/// Names a host object for the device-removed report, which names the +/// allocations a page fault hit (only with device-removed data on). +pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { + if dred_on() + && let Ok(object) = object.cast::() + { + // SAFETY: a plain call on a live object. + let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) }; + } +} + +/// One in [`ALIVE`]`[0]` while it lives (a host list), and one in +/// [`LISTS`]`[3]` until it is first reset. +struct Counted { + /// Not reset since it was made. + fresh: std::sync::atomic::AtomicBool, +} + +impl Counted { + fn new() -> Counted { + ALIVE[0].fetch_add(1, Ordering::Relaxed); + LISTS[3].fetch_add(1, Ordering::Relaxed); + Counted { + fresh: std::sync::atomic::AtomicBool::new(true), + } + } + + /// The list is reset: it is in use. + fn used(&self) { + if self.fresh.swap(false, Ordering::Relaxed) { + LISTS[3].fetch_sub(1, Ordering::Relaxed); + } + } +} + +impl Drop for Counted { + fn drop(&mut self) { + ALIVE[0].fetch_sub(1, Ordering::Relaxed); + self.used(); + } +} + +/// A chunk of upload memory for lists' scratch data: the buffer, its +/// mapping and its host GPU address. +struct Chunk { + _buffer: ID3D12Resource, + data: usize, + gpu: u64, +} + +// SAFETY: a D3D12 resource (free-threaded) and its persistent mapping, +// written only by the list that holds the chunk. +unsafe impl Send for Chunk {} + +/// Upload chunks handed out front to back: the chunks (each with its +/// bytes), the one in use and the bytes used in it. +#[derive(Default)] +struct Scratch { + chunks: Vec<(Chunk, u64)>, + current: usize, + used: u64, +} + +// SAFETY: the chunk pointers are persistent mappings of upload buffers. +unsafe impl Send for Scratch {} + +impl Drop for Scratch { + fn drop(&mut self) { + give_chunks(std::mem::take(&mut self.chunks)); + } +} + +const SCRATCH_CHUNK: u64 = 4 << 20; +/// A list's first chunk when the chunks are shared ([`scratch_pool`]): most +/// lists put a few constants or a rectangle's corners there, and every +/// list that did took 4 MiB of the PC's memory for it. +const SCRATCH_FIRST: u64 = 256 << 10; +/// The most bytes of chunks kept while no list holds them. +const SPARE_MOST: u64 = 128 << 20; + +/// Whether lists share their scratch chunks: a list takes a chunk when it +/// first needs one, a small one first, and gives all of them back when it +/// is reset or dropped, for the next list. Before, a list kept every chunk +/// it ever took (4 MiB each) for as long as it lived, used or not, and the +/// host lists of held submissions, which live for one submission, each +/// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and +/// freed per frame of gameplay (run 60). +/// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before. +fn scratch_pool() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0")) +} + +/// Things of some sizes that nothing holds now, kept for whoever next asks +/// for one of the same size. +struct Spare { + kept: Vec<(T, u64)>, + bytes: u64, +} + +impl Spare { + const fn new() -> Self { + Spare { kept: Vec::new(), bytes: 0 } + } + + /// A kept thing of `size` bytes, the one given last. + fn take(&mut self, size: u64) -> Option { + let at = self.kept.iter().rposition(|(_, s)| *s == size)?; + self.bytes -= size; + Some(self.kept.remove(at).0) + } + + /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past + /// `most`: then it comes back. + fn give(&mut self, thing: T, size: u64, most: u64) -> Option { + if self.bytes + size > most { + return Some(thing); + } + self.bytes += size; + self.kept.push((thing, size)); + None + } +} + +/// Scratch chunks no list holds. +static SPARE: Mutex> = Mutex::new(Spare::new()); + +/// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one. +fn take_chunk(host: &Host, size: u64) -> Option { + if scratch_pool() + && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size) + { + ALIVE[3].fetch_sub(1, Ordering::Relaxed); + ALIVE[4].fetch_sub(size, Ordering::Relaxed); + ALIVE[5].fetch_add(1, Ordering::Relaxed); + return Some(chunk); + } + let (buffer, data) = host.upload_buffer(size)?; + name(&buffer, || "list scratch".into()); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + ALIVE[1].fetch_add(1, Ordering::Relaxed); + ALIVE[2].fetch_add(size, Ordering::Relaxed); + Some(Chunk { + _buffer: buffer, + data: data as usize, + gpu, + }) +} + +/// A list is done with `chunks` (it was reset after its submissions ran, +/// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and +/// without the pool. +fn give_chunks(chunks: Vec<(Chunk, u64)>) { + if chunks.is_empty() { + return; + } + let mut freed = Vec::new(); + { + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + for (chunk, size) in chunks { + let back = if scratch_pool() { + spare.give(chunk, size, SPARE_MOST) + } else { + Some(chunk) + }; + match back { + None => { + ALIVE[3].fetch_add(1, Ordering::Relaxed); + ALIVE[4].fetch_add(size, Ordering::Relaxed); + } + Some(chunk) => { + ALIVE[1].fetch_sub(1, Ordering::Relaxed); + ALIVE[2].fetch_sub(size, Ordering::Relaxed); + freed.push(chunk); + } + } + } + } + // Freed outside the lock. + drop(freed); +} + +/// What the host keeps for copies in the card's own memory +/// ([`crate::shadow::cards`]): three lists of ours and the compare. +struct CardWork { + /// Before a submission's lists: what changed on the copies' CPU side + /// goes to their card side. Those not in use: a plan takes one and + /// gives it back when its submission has run (`Host::card_done`), so + /// that submissions sent ahead ([`late`]) each have their own. + sync: Vec, + /// After them, in the same submission: the compare of the declared + /// ranges with their bytes from before. As `sync`. + check: Vec, + /// After it ran: the pieces that differ come down. + fetch: Prelude, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// One dword per piece compared, set where the piece differs: PC + /// memory, mapped (buffer, mapping, bytes). + differs: (ID3D12Resource, usize, u64), + /// Where the pieces that differ are fetched to: PC memory, mapped. + fetched: Option<(ID3D12Resource, usize, u64)>, + /// The dwords of `differs` taken by plans whose results were not read + /// yet. + taken: u32, + /// Plans made and not done with (`Host::card_done`). + out: u32, +} + +// SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only +// under the submission lock. +unsafe impl Send for CardWork {} + +static CARD_WORK: Mutex> = Mutex::new(None); + +/// The compare of a declared range of a copy in the card's memory with +/// its bytes from before, one thread per 64 KiB piece (cut at multiples of +/// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs` +/// gets a dword per piece, 1 where a byte differs. The offsets are widened +/// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a +/// byte just outside the range costs a fetch that finds nothing. +pub(crate) const CARD_COMPARE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)" +cbuffer Span : register(b0) { + uint first; // the first piece + uint skew; // where the copy starts in its piece 0 + uint size; // the copy's buffer, in bytes (a multiple of 64 KiB) + uint pieces; + uint out_at; // the first piece's dword in `differs`, in bytes + uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored) +}; +ByteAddressBuffer now : register(t0); +// 16 bytes per piece of the copy: the hash of its bytes when they were +// last sent up (or hashed whole, the first time). +RWByteAddressBuffer hashes : register(u0); +RWByteAddressBuffer differs : register(u1); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= pieces) return; + uint piece = first + id.x; + uint lo = piece * 65536u; + lo = lo > skew ? lo - skew : 0u; + uint hi = min((piece + 1u) * 65536u - skew, size); + lo = lo & ~15u; + hi = (hi + 15u) & ~15u; + uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu); + [loop] + for (uint at = lo; at < hi; at += 16u) { + h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + } + if (compare != 0u) { + differs.Store(out_at + id.x * 4u, any(h != hashes.Load4(piece * 16u)) ? 1u : 0u); + // With the copy-back on its own thread: the next compare of the + // piece finds what is written from here on. + if (compare == 2u) hashes.Store4(piece * 16u, h); + } else { + hashes.Store4(piece * 16u, h); + } +} +"#; + +/// Whether the pieces hashed again after ranges were sent up to a copy in +/// the card's memory are hashed in runs of pieces that touch, each piece +/// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass +/// per range sent up. +/// +/// These passes are ours, they run on the card before every submission's +/// lists, and no timing so far names them: each walks its 64 KiB pieces +/// 16 bytes at a time, 4,096 steps one after the other, so a pass takes +/// the time of one piece however few its pieces are. Run 102 sent up 514 +/// ranges a frame: 514 such passes. The same pieces are hashed either way; +/// a piece hashed when it need not be, or not hashed when it should, costs +/// a fetch that finds nothing and loses no shader write. +fn rehash_runs() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1")) +} + +/// Since the last frame-rate line, of our own passes over copies in the +/// card's memory: hash passes after ranges were sent up, the pieces they +/// hashed, and compare passes after the lists. +static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Whether what shaders wrote to copies in the card's memory is merged +/// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by +/// default). The pieces the card's compare found differing come down in +/// one fetch and were then merged one after the other on the thread that +/// settles: about 630 pieces and 40 MB a frame (run 104), each compared +/// with the copy's CPU side byte by byte and put into title memory through +/// the kernel. A piece is its own bytes of its copy and of title memory, +/// so eight threads take an eighth of them each. +fn wide_merge() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1")) +} + +/// One declared range of a copy in the card's memory, in a submission. +struct CardRange { + shadow: std::sync::Arc, + /// As declared (title addresses), for the statistics. + declared: (usize, usize), + span: crate::shadow::CardSpan, + /// Its first piece's dword in the compare's results. + at: u32, + /// Whether the card compares it; else every piece is fetched. + compared: bool, +} + +/// What a submission does for copies in the card's memory. +struct CardPlan { + ranges: Vec, + /// The compare, run after the submission's lists. + check: Option, + /// The copies whose card side was brought up to date, alive until the + /// submission has run. + _synced: Vec>, + /// The lists of ours the plan recorded (whether the compare, the + /// list), given back by `Host::card_done`. + lists: Vec<(bool, Prelude)>, +} + +/// One piece of submission-time work, in recorded order. +enum Step { + /// A copy into title memory (destination, source, bytes): the title's + /// buffer copies, which later refreshes must see. + Copy(usize, usize, usize), + /// A copy of title memory into the list's own upload memory. + Fill(usize, usize, usize), + /// Brings a range (address, bytes) of a buffer's host copy up to date: + /// once per submission, whichever lists ask, until a `Copy` or `Run` + /// intervenes. + Refresh(std::sync::Arc, usize, usize), + /// Work that may write title memory. + Run(Box), + /// Work that writes host memory only. + Host(Box), + /// Shaders write a range (address, bytes) of a buffer's host copy. + GpuWrite(std::sync::Arc, usize, usize), + /// 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), +} + +/// What a list does on the CPU when it is submitted: copies between host +/// memory regions (title buffers, upload buffers and buffer copies), and +/// the upload buffers its GPU commands read, kept until the list is reset. +#[derive(Default)] +struct Deferred { + /// Destination, source, bytes. + copies: Vec, + uploads: Vec, + /// The bytes of `uploads` (counted in [`ALIVE`] while they are held). + upload_bytes: u64, + /// Host objects the list's commands name (pipelines, root signatures, + /// descriptor heaps): the title may release its objects before it + /// submits the list. + kept: Vec, + /// Buffer ranges refreshed since the last title copy (host copy, + /// address, bytes): refreshing them again would find the same bytes. + refreshed: std::collections::HashSet<(usize, usize, usize)>, + /// Textures whose contents the list brings up to date. + textures: std::collections::HashSet, + /// Bottom-of-pipe writes, done once the list has run: address, what, + /// bytes. + writes: Vec<(usize, crate::queue::Written, usize)>, + /// Textures read back (texture to buffer copies), done once the list + /// has run: the host buffer the list copies the texels into, the title + /// memory they go to, the bytes of a row, the rows, the title's row + /// pitch. + backs: Vec<(ID3D12Resource, usize, [usize; 3])>, + /// Whether a step zeroes the indirect-work budget. + budget_zeroed: bool, +} + +impl Deferred { + /// Holds `buffer` (`size` bytes of upload memory) until the list is + /// reset. + fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) { + ALIVE[6].fetch_add(1, Ordering::Relaxed); + ALIVE[7].fetch_add(size, Ordering::Relaxed); + self.upload_bytes += size; + self.uploads.push(buffer); + } +} + +impl Drop for Deferred { + fn drop(&mut self) { + ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed); + ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed); + } +} + +/// Whether a queue's submissions go to the card without a wait for each +/// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which +/// waits for every list on its own). +/// +/// Every submission was prepared, sent, waited for and copied back before +/// the next one was looked at, so the card stood idle while we prepared +/// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of +/// preparing, 194 ms of waiting and 78 ms of copying back, one after the +/// other, on the one thread that submits. +/// +/// With the switch a queue's submission is sent and joins a line of +/// "flights" ([`Flight`]); the thread goes on to the next one while the +/// card runs. The flights are settled together ([`Host::settle`]: one wait +/// for the card, what their shaders wrote copied back once per byte, then +/// their bottom-of-pipe writes and the fence signals behind them, in +/// order) at the next point where the title, or our own preparing, can +/// observe what they do. Those points, exactly: +/// +/// 1. a synchronous submission of ours ([`Host::execute`]): a present, a +/// read-back or map of a texture, a clear or upload run at once; +/// 2. the next submission reads title memory that a flight's shaders may +/// write: a title buffer copy, a fill of upload memory, a texture's +/// memory, any step that runs code of ours on title memory +/// ([`late_blocked`]); +/// 3. the next submission refreshes a range of a host copy that a flight's +/// shaders may write, and the title wrote a page of it since it was last +/// copied ([`stale_under_flights`]): the refresh leaves such a range +/// alone until the flight's writes are back, as it always did within a +/// submission; +/// 4. a queue stands at a wait for a memory value that no flight's +/// bottom-of-pipe write is known to satisfy, at an address a flight may +/// write ([`late_met`]); +/// 5. the title blocks on a fence without an event; +/// 6. the card has run every flight (a thread of ours waits for that: +/// [`late_helper`]), or the flights hold [`late_most`] host lists. +/// +/// What the title is told (bottom-of-pipe writes, fence values) is told +/// when the card has really run the work, later than before and never +/// earlier; a fence signalled on a queue while flights are in the air is +/// set behind them. A wait for a memory value that a flight's +/// bottom-of-pipe write satisfies counts as met: the waiting part goes to +/// the card behind that flight, which is the order the wait asks for. +/// +/// What it assumes beyond today: memory the title rewrites between two of +/// its submissions, without waiting for the first, may be seen by the +/// first's shaders (as on the console, where the card reads title memory +/// when it runs, not when the list is submitted). +pub(crate) fn late() -> bool { + late_stage() > 0 +} + +/// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]). +fn late_stage() -> u8 { + static STAGE: OnceLock = OnceLock::new(); + *STAGE.get_or_init(|| { + if std::env::var_os("VICTORY_GPU_TIMING").is_some() { + return 0; + } + match std::env::var("VICTORY_LATE_WAIT").as_deref() { + Ok("1") => 1, + Ok("2") => 2, + Ok("3") => 3, + // The relay alone: on top of stage 3. + Err(_) if crate::shadow::relay() => 3, + _ => 0, + } + }) +} + +/// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no +/// longer a point. Where the title wrote a page that lies in a range a +/// flight's shaders may write, the bytes the title changed are found (the +/// page as it is now against what the copy held when the flight was +/// prepared) and put into the copy, and only those: what the flight's +/// shaders write beside them stays (`Shadow::merge_under_writes`). The +/// flights are settled for it only where that cannot be done: memory that +/// is not write-watched, or a copy in the card's memory with more changed +/// runs than a submission should send up one by one. +/// +/// In run 92 (stage 1) this point settled the flights five times a frame +/// of twelve, each time with the card's work still to wait for: 172 ms a +/// frame of waiting were left of 200. +/// +/// What differs from settling first: a byte both the title and a flight's +/// shader wrote is the title's if the shader wrote it first, the shader's +/// if it wrote it afterwards; settled first it was always the shader's. +/// The title writing a byte a shader of its own is writing is a race on +/// the console too. +fn late_exact() -> bool { + late_stage() > 1 +} + +/// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is +/// no longer a point where flights are settled). The copy to the back +/// buffer is sent as a flight of its own (`Host::execute_own`, a list of +/// its own for each present in the air) and the swap chain is told to +/// present behind it; the queue's call returns, and the card finishes the +/// frame while the title records the next one. What the title is told +/// about the frame (bottom-of-pipe writes, fences) is told when the card +/// has run it, by the settling thread. +/// +/// What is left out with it: the look whether the presented frame is black +/// (diagnostics; it reads the frame back at once). A frame that is saved +/// or listed is presented the old way. Once every second and a half a +/// submission settles the flights all the same, for the sweep that lets +/// idle host objects go (it needs nothing in the air). +pub(crate) fn late_free_present() -> bool { + late_stage() > 2 +} + +/// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns +/// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage, +/// and is off with it, in the timing run and with kept snapshots). +/// +/// With [`late`] alone every settle does three things on the thread that +/// holds the submission lock: it waits for everything in the air, copies +/// back with the card standing, and only then goes on preparing. The frame +/// stays a relay: the card works about 242 ms of it and one thread +/// prepares, waits and copies back for about 220. +/// +/// With the switch a thread of its own ([`relay_worker`]) lands flights as +/// soon as the card has run them, in the order they were sent and without +/// the submission lock: it fetches and merges what their shaders wrote to +/// copies in the card's memory, compares and merges the other copies, +/// frees the flights' ranges, and then does their read-backs, their +/// bottom-of-pipe writes and the fence signals behind them, in the line's +/// order. The submitting thread meanwhile prepares and sends the next +/// submissions. [`Host::settle`] no longer settles anything: it waits until +/// that thread has landed everything in the air, at the same points as +/// before (the list in [`late`]), so whoever can observe title memory, a +/// fence or a present still does so only after the flights before it are +/// merged. +/// +/// What makes that safe is in `crate::shadow::relay` (ranges counted per +/// flight; a merge that never stores into memory the card may be writing; +/// sends to card copies numbered) and here: flights land in the order of +/// [`LINE`] by one thread, so a later flight's results never reach title +/// memory before an earlier flight's; the compare on the card stores the +/// hash it made, so each flight's compare flags exactly what changed since +/// the compare before it, however late the pieces are fetched; the fetch +/// goes to the queue under [`QUEUE_ORDER`], which says which sends of +/// title bytes the card had received when it ran. +pub(crate) fn relay() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay()) +} + +/// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads +/// title memory a flight's shaders may write (a title buffer copy, a fill +/// of upload memory, a texture) waits only until the flights that declared +/// that memory have landed, not for everything in the air; and at +/// [`late_most`] lists in the air it waits until there are fewer. At `1` +/// both wait for everything. +fn relay_exact() -> bool { + static ON: OnceLock = OnceLock::new(); + // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default + // since the walls of the first room were found drawn in every run with + // this set and in fewer than half without it). + *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2")) +} + +/// Told when something joins [`LINE`], for the thread that lands flights +/// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at +/// what queues hold. +static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new(); + +/// Told when flights have landed ([`relay`]): who waits for that looks +/// again. +static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new(); + +/// With [`relay`], the order of what we put on the queue: the number of +/// sends of changed ranges to copies in the card's memory so far +/// (`Host::card_before`). Held from the taking of the ranges until their +/// list is on the queue, and while a fetch of pieces goes to the queue: a +/// fetch sent with the count at N ran behind sends 1..N and ahead of every +/// later one. +static QUEUE_ORDER: Mutex = Mutex::new(0); + +/// Since the last frame-rate line, of the thread that lands flights +/// ([`relay`]): landings, flights landed, microseconds it waited for the +/// card with nothing to land, microseconds it waited for fetches of card +/// copies' pieces, microseconds of landing in all. +static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// Of the line's things in order (a flight: the value signalled on the +/// host's fence behind it; a write or a signal behind a flight: `None`): +/// how many, from the front, can be landed when the card has reached +/// `completed`: everything ahead of the first flight it has not run. A +/// later flight never lands before an earlier one, and what follows a +/// flight (its bottom-of-pipe writes, signals) never before the flight. +fn landable(line: &[Option], completed: u64) -> usize { + line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len()) +} + +/// For one plan of copies in the card's memory, with [`relay`]: `flags` +/// holds, for every piece of every range of the plan, the copy, the +/// piece's number in the copy and whether the compare flagged it there (or +/// did not run). The pieces to fetch, under whichever range: all of them +/// flagged under any. Two ranges of a plan may hold parts of the same +/// 64 KiB piece; the compare hashes the whole piece for each and stores +/// the hash, so the second of them may find it stored already and not +/// flag it. +fn flagged_pieces(flags: &[(usize, u32, bool)]) -> std::collections::HashSet<(usize, u32)> { + flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect() +} + +#[cfg(test)] +mod relay_tests { + use super::{flagged_pieces, landable}; + + /// Two flights and what follows each: nothing of the second lands + /// before the card has run it, and nothing behind a flight lands + /// before the flight. + #[test] + fn flights_land_in_the_order_they_were_sent() { + // Flight (fence 5), its write, a signal, flight (fence 6), its write. + let line = [Some(5), None, None, Some(6), None]; + assert_eq!(landable(&line, 4), 0); + assert_eq!(landable(&line, 5), 3); + assert_eq!(landable(&line, 6), 5); + assert_eq!(landable(&line, u64::MAX), 5); + // Signals with no flight ahead land at once; behind one they wait. + assert_eq!(landable(&[None, None], 0), 2); + assert_eq!(landable(&[None, Some(9), None], 8), 1); + assert_eq!(landable(&[], 3), 0); + // After the first three landed, the rest when its turn comes. + assert_eq!(landable(&line[3..], 5), 0); + assert_eq!(landable(&line[3..], 6), 2); + } + + /// A piece flagged under one range of a plan is fetched under every + /// range that holds a part of it; pieces of other copies are not. + #[test] + fn a_piece_flagged_under_one_range_is_fetched_under_all() { + let (a, b) = (0x1000usize, 0x2000usize); + // Copy a: piece 3 under two ranges, flagged under the first only; + // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged. + let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)]; + let fetch = flagged_pieces(&flags); + assert!(fetch.contains(&(a, 3))); + assert!(!fetch.contains(&(a, 4))); + assert!(!fetch.contains(&(b, 3))); + assert!(fetch.contains(&(b, 9))); + assert_eq!(fetch.len(), 2); + } +} + +/// The most host lists in the air before the flights are settled +/// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the +/// relay it stopped the submitting thread twice a frame for 92-103 ms in +/// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162; +/// 32 settled the flights three times a +/// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables +/// asked and none refused; watch "tables asked, N refused"): their dynamic +/// descriptor slots, upload +/// memory and scratch chunks are held until then, and a frame's lists held +/// all at once ran the slots out before (run 45). +fn late_most() -> usize { + static MOST: OnceLock = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1) + }) +} + +/// Whether a submission with bottom-of-pipe writes may fly +/// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so +/// the title is told at once, as before; for telling a title that polls +/// such a value from one that does not). +fn late_writes() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0")) +} + +/// Per host copy, the ranges a submission's shaders may write, as declared +/// (address, end). +type Declared = (std::sync::Arc, Vec<(usize, usize)>); + +/// What [`Host::submit`] hands back for a submission it sent and did not +/// wait for. +struct Sent { + /// Its number among the submissions started. + number: u64, + card: Option, + back: Vec, + /// Its bottom-of-pipe writes. + writes: Vec<(usize, crate::queue::Written, usize)>, +} + +/// A submission on the card that has not been waited for ([`late`]): its +/// host lists, taken from the title's (which it may reset meanwhile), and +/// what is to be done once it has run. +struct Flight { + number: u64, + /// The value signalled on the host's fence behind it. + fence: u64, + lists: Vec, + order: Vec, + card: Option, + back: Vec, +} + +/// One thing in the line of what waits for the card, in order. +enum Late { + Run(Flight), + /// A bottom-of-pipe write of the flight before it: address, what, bytes. + Write(usize, crate::queue::Written, usize), + /// A fence (its address) signalled behind the flights before it. + Signal(usize, u64), +} + +struct Line { + line: Vec, + /// The title memory the flights' shaders may write (address, end), in + /// order and joined. + written: Vec<(usize, usize)>, + /// Host lists in the flights. + lists: usize, + /// The value signalled on the host's fence behind the last flight. + target: u64, + /// A settle has taken the line and is not done: a signal still goes + /// behind it. + settling: bool, + /// Something was settled away from a queue's own calls: the helper + /// thread looks at what queues hold. + poke: bool, + /// Host lists of settled flights, reset and given back outside the + /// submission lock ([`land`]: a settle may run under a caller's own + /// locks). + landed: Vec<(Vec, Vec)>, + /// With [`relay`]: the bottom-of-pipe writes of the flights being + /// landed (taken out of `line`, not done yet), for [`late_met`]. + in_hand: Vec<(usize, crate::queue::Written, usize)>, +} + +// SAFETY: D3D12 objects (free-threaded) and host lists nothing records +// into; touched under the lock. +unsafe impl Send for Line {} + +static LINE: Mutex = Mutex::new(Line { + line: Vec::new(), + written: Vec::new(), + lists: 0, + target: 0, + settling: false, + poke: false, + landed: Vec::new(), + in_hand: Vec::new(), +}); +/// Told when a flight joins [`LINE`] or it is poked. +static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new(); + +fn line() -> std::sync::MutexGuard<'static, Line> { + LINE.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Why flights were settled ([`LATE_STATS`]' places from 2 on). +const WHY_SYNC: usize = 2; +const WHY_CARD_DONE: usize = 3; +const WHY_VALUE: usize = 4; +const WHY_STALE: usize = 5; +const WHY_READ: usize = 6; +const WHY_RUN: usize = 7; +const WHY_MOST: usize = 8; +const WHY_WRITES: usize = 9; +const WHY_FENCE: usize = 10; + +/// Since the last frame-rate line: submissions sent without a wait; +/// settles; settles by reason ([`WHY_SYNC`]..); flights settled; +/// microseconds settles waited for the card; value waits met by a flight's +/// bottom-of-pipe write; fence signals set behind flights. +/// Then: the settles for title memory read, by what read it (a buffer +/// copy, a fill of upload memory, a texture). +static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18]; + +/// Since the last frame-rate line: the microseconds settles waited for the +/// card, by why they settled (the `WHY_` places). +static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; + +/// Whether `[from, to)` touches one of `ranges` (in order, joined). +fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool { + if from >= to { + return false; + } + let at = ranges.partition_point(|r| r.1 <= from); + ranges.get(at).is_some_and(|r| r.0 < to) +} + +/// `ranges` with `more`, in order, joined where they overlap or touch. +fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator) { + ranges.extend(more.into_iter().filter(|r| r.0 < r.1)); + ranges.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for &(from, to) in ranges.iter() { + match out.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => out.push((from, to)), + } + } + *ranges = out; +} + +/// Whether anything is in the air. +fn flying() -> bool { + if !late() { + return false; + } + let line = line(); + // (With the relay: also while flights are being landed.) + line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_))) +} + +/// With flights in the air ([`late`]): why `runs` cannot be prepared +/// before they are settled, if so. Preparing reads title memory on the +/// CPU (the title's buffer copies, fills of upload memory, textures) and +/// runs steps of ours that may read or write it anywhere; what the +/// flights' shaders write is not there yet. +fn late_blocked(runs: &[&HostList]) -> Option { + let written = { + let line = line(); + if line.written.is_empty() { + return None; + } + line.written.clone() + }; + blocked_by(&written, runs, true) +} + +/// [`late_blocked`] against `written`, the title memory flights' shaders +/// may write (in order, joined); `count` whether the kind of read is +/// counted for the frame line. +fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option { + if written.is_empty() { + return None; + } + for list in runs { + for step in &list.deferred().copies { + match step { + &Step::Copy(dst, src, len) => { + if touches(written, src, src + len) || touches(written, dst, dst + len) { + if count { + LATE_STATS[15].fetch_add(1, Ordering::Relaxed); + } + return Some(WHY_READ); + } + } + &Step::Fill(_, src, len) => { + if touches(written, src, src + len) { + if count { + LATE_STATS[16].fetch_add(1, Ordering::Relaxed); + } + return Some(WHY_READ); + } + } + Step::Texture(staging) => { + let (at, len) = staging.memory(); + if touches(written, at, at + len) { + if count { + LATE_STATS[17].fetch_add(1, Ordering::Relaxed); + } + return Some(WHY_READ); + } + } + Step::Run(_) => return Some(WHY_RUN), + Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(_) => {} + } + } + } + None +} + +/// With flights in the air, after the submission's write-watch asking: +/// whether `runs` refresh a range of a host copy that a flight's shaders +/// may write and that the title wrote since it was last copied. The +/// refresh leaves ranges shaders are writing alone (`Shadow::update`), so +/// the title's bytes there would reach the card a submission late. +fn stale_under_flights(runs: &[&HostList]) -> bool { + use std::sync::Arc; + // Per copy, the span of what is refreshed (a flush brings that much + // up to date at most). + let mut spans: Vec<(Arc, usize, usize)> = Vec::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::Refresh(shadow, address, len) = step + && shadow.writes_pending() + { + match spans.iter_mut().find(|s| Arc::ptr_eq(&s.0, shadow)) { + Some(s) => (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len)), + None => spans.push((shadow.clone(), *address, *address + *len)), + } + } + } + } + if late_exact() { + // The title's bytes are put in beside the flights' writes; a + // settle is still due where that could not be done. At most this + // many changed runs go up to copies in the card's memory, each a + // copy of its own there. + let mut runs_left = 512; + return spans.iter().any(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left)); + } + spans.iter().any(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from)) +} + +/// A fence signal on a queue ([`late`]): goes behind the flights in the +/// air, if there are any, and is set when they are settled. Whether it +/// did; if not the caller sets the fence now. +pub(crate) fn late_signal(fence: usize, value: u64) -> bool { + if !late() { + return false; + } + let mut line = line(); + if line.line.is_empty() && !line.settling { + return false; + } + line.line.push(Late::Signal(fence, value)); + LATE_STATS[14].fetch_add(1, Ordering::Relaxed); + drop(line); + // A signal alone (behind a settle under way) has no flight to wake + // the helper thread for it. + LINE_MOVED.notify_one(); + RELAY_MOVED.notify_one(); + true +} + +/// A queue stands at `wait`, which memory does not meet now ([`late`]): +/// whether it is met once the flights in the air have run. A flight's +/// bottom-of-pipe write of a value that meets it says yes without a wait +/// for the card: the part behind the wait goes to the card behind that +/// flight, which is the order the wait asks for. If the flights may write +/// the value in a way not known here (shaders, a timestamp, another +/// width), they are settled and memory is asked again. +pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool { + let (address, bytes) = wait.place(); + { + let line = line(); + if line.line.is_empty() && line.in_hand.is_empty() { + return false; + } + let mut unsure = touches(&line.written, address, address + bytes); + // (With the relay: first the writes of flights being landed.) + let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item { + Late::Write(at, what, n) => Some((at, what, n)), + _ => None, + })); + for (at, what, n) in writes { + if *at >= address + bytes || address >= *at + *n { + continue; + } + match what { + crate::queue::Written::Value(v) if *at == address && *n >= bytes => { + if wait.holds_for(*v) { + LATE_STATS[13].fetch_add(1, Ordering::Relaxed); + return true; + } + } + _ => unsure = true, + } + } + if !unsure { + return false; + } + } + settle_now(WHY_VALUE); + wait.met() +} + +/// Settles the flights in the air, if any ([`Host::settle`]), for reason +/// `why` (one of the `WHY_` places). Not from inside a submission. +pub(crate) fn settle_now(why: usize) { + if !late() { + return; + } + let Some(host) = host() else { + return; + }; + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + host.settle(&mut submitted, why); +} + +/// [`settle_now`] at a present, and for a fence the title blocks on. +pub(crate) fn settle_for_present() { + settle_now(WHY_SYNC); +} +pub(crate) fn settle_for_fence() { + settle_now(WHY_FENCE); +} + +/// Resets the host lists of settled flights and keeps them for reuse, as +/// a queue does for the lists it ran (`crate::list::recycle`). +fn land() { + let landed = std::mem::take(&mut line().landed); + for (lists, order) in landed { + crate::list::recycle(lists, &order); + } +} + +/// The thread that settles the flights once the card has run them all +/// ([`late`]): without it a bottom-of-pipe write would reach the title only +/// at the next call that settles, and a title thread that polls such a +/// value while the submitting thread waits for that thread would never +/// see it. +fn late_helper() { + let Some(host) = host() else { + return; + }; + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + tracing::warn!("no event for the thread that settles submissions sent ahead"); + return; + }; + loop { + let target = { + let mut line = line(); + loop { + if line.poke { + line.poke = false; + break None; + } + // (With the relay the flights are another thread's.) + if !relay() && !line.line.is_empty() && !line.settling { + break Some(line.target); + } + line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner()); + } + }; + let Some(target) = target else { + land(); + crate::queue::release_held(false); + continue; + }; + // The card first, without the submission lock: the submitting + // thread prepares and sends meanwhile. + // SAFETY: our fence and event. + unsafe { + if host.fence.SetEventOnCompletion(target, event).is_ok() { + WaitForSingleObject(event, INFINITE); + } + } + { + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + // Something newer went up meanwhile: the card is waited for + // again, the submitting thread is not held up for it. + if line().target != target { + continue; + } + host.settle(&mut submitted, WHY_CARD_DONE); + } + land(); + crate::queue::release_held(false); + } +} + +/// Starts the threads of [`late`], once: the one that settles flights when +/// the card has run them and looks at what queues hold, and with [`relay`] +/// the one that lands flights. +fn late_threads() { + static HELPER: std::sync::Once = std::sync::Once::new(); + HELPER.call_once(|| { + if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) { + tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow"); + } + tracing::info!( + most = late_most(), + writes = late_writes(), + "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)" + ); + if relay() { + // Without it nothing would ever land. + if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) { + fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}")); + } + tracing::info!( + exact = relay_exact(), + "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)" + ); + } + }); +} + +/// With [`relay`]: waits until `done` says so of the line, looked at each +/// time flights have landed. Counted as a settle for `why`, and its time +/// as waiting for the card. The caller may hold the submission lock: the +/// thread that lands flights never takes it. +fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { + let mut line = line(); + if done(&line) { + return; + } + LATE_STATS[1].fetch_add(1, Ordering::Relaxed); + LATE_STATS[why].fetch_add(1, Ordering::Relaxed); + let was_working = working(false); + let waiting = std::time::Instant::now(); + while !done(&line) { + line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner()); + } + drop(line); + stood(waiting); + working(was_working); + let us = waiting.elapsed().as_micros() as u64; + LATE_STATS[12].fetch_add(us, Ordering::Relaxed); + LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed); + SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed); +} + +/// What the thread that lands flights fetches card copies' pieces with +/// ([`relay`]): a list, a fence and an event of its own (the host's are +/// behind the submission lock), and the memory the pieces come down to. +struct RelayFetch { + list: Prelude, + fence: ID3D12Fence, + event: HANDLE, + /// The last value signalled on `fence`. + sent: u64, + /// Buffer, mapping, bytes. + buffer: Option<(ID3D12Resource, usize, u64)>, +} + +/// The thread that lands flights ([`relay`]): as soon as the card has run +/// the first flights of the line it takes them, with what follows them, +/// and does what they left to do ([`Host::relay_land`]); else it waits for +/// the card, or for a flight. It takes neither the submission lock nor +/// anything a caller of [`Host::settle`] may hold: resetting the landed +/// lists and looking at what queues hold are left to [`late_helper`]. +fn relay_worker() { + let Some(host) = host() else { + return; + }; + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)")); + }; + let mut fetch: Option = None; + loop { + let next = { + let mut line = line(); + loop { + if line.line.is_empty() { + line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner()); + continue; + } + let fences: Vec> = line + .line + .iter() + .map(|l| match l { + Late::Run(flight) => Some(flight.fence), + _ => None, + }) + .collect(); + // SAFETY: a plain query. + let completed = unsafe { host.fence.GetCompletedValue() }; + let n = landable(&fences, completed); + if n == 0 { + // The first thing is a flight the card has not run. + break Err(fences[0].unwrap_or(0)); + } + line.settling = true; + let items: Vec = line.line.drain(..n).collect(); + line.in_hand = items + .iter() + .filter_map(|l| match l { + Late::Write(at, what, bytes) => Some((*at, *what, *bytes)), + _ => None, + }) + .collect(); + break Ok(items); + } + }; + match next { + Ok(items) => host.relay_land(items, &mut fetch), + Err(target) => { + let waiting = std::time::Instant::now(); + // SAFETY: the host's fence and this thread's event. + let waited = unsafe { + host.fence.SetEventOnCompletion(target, event).map(|()| { + WaitForSingleObject(event, INFINITE); + }) + }; + if waited.is_err() { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + } + } + } +} + +/// [`relay`]: what shaders wrote to the declared ranges `back` of copies +/// in the PC's memory goes into title memory. As [`hand_back`], each byte +/// once, the pieces that differ found on several threads; but the merge is +/// `Shadow::relay_merge`, which does not write the copy, and the ranges +/// are not done with here (each flight's are, afterwards). +fn relay_hand_back(back: &[Declared]) { + let mut work: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); + for (shadow, declared) in back { + if shadow.carded() { + continue; + } + let mut spans: Vec<(usize, usize)> = Vec::new(); + join_ranges(&mut spans, declared.iter().copied()); + for &(from, to) in &spans { + shadow.relay_compared(from, to - from); + } + work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to))); + } + if work.is_empty() { + return; + } + #[cfg(feature = "diagnostics")] + let scanning = std::time::Instant::now(); + // Looked through without a lock: a piece that changes meanwhile (a + // later flight writing, the title's bytes going in) is found now or by + // that flight's landing, and the merge looks again under the lock. + let found = crate::shadow::find_all(&work); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); + let (mut now, mut title) = (Vec::new(), Vec::new()); + for ((shadow, from, to), found) in work.iter().zip(found) { + let mut written = 0; + for (at, n) in found { + written += shadow.relay_merge(at, n, &mut now, &mut title); + } + COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(*from, to - from, written); + let _ = (from, to); + } +} + +/// For the frame-rate line, with [`late`]: what the line of flights did +/// per frame since the last one. +fn late_line(frames: f64) { + if !late() { + return; + } + let s: Vec = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \ + settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \ + title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \ + a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \ + bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \ + {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights", + s[0], + s[1], + if s[1] > 0.0 { s[11] / s[1] } else { 0.0 }, + s[12] / 1000.0, + s[WHY_SYNC], + s[WHY_CARD_DONE], + s[WHY_VALUE], + s[WHY_STALE], + s[WHY_READ], + s[15], + s[16], + s[17], + s[WHY_RUN], + late_most(), + s[WHY_MOST], + s[WHY_WRITES], + s[WHY_FENCE], + s[13], + s[14], + ); + { + let w: Vec = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect(); + tracing::info!( + "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \ + the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \ + title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}", + w[WHY_SYNC], + w[WHY_CARD_DONE], + w[WHY_VALUE], + w[WHY_STALE], + w[WHY_READ], + w[WHY_RUN], + w[WHY_MOST], + w[WHY_WRITES], + w[WHY_FENCE], + ); + } + if relay() { + let r: Vec = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \ + beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \ + fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \ + \"settles\" above are waits of other threads for it)", + r[1], + r[0], + r[2] / 1000.0, + r[3] / 1000.0, + r[4] / 1000.0, + ); + } + if late_exact() { + let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames); + tracing::info!( + "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \ + {runs:.0} changed runs, {:.2} MB", + bytes / (1 << 20) as f64 + ); + } +} + +#[cfg(test)] +mod late_tests { + use super::{continues, join_ranges, touches}; + + /// Copies join only when both ends continue and the whole does not + /// overlap itself. + #[test] + fn copies_join_only_end_to_end_and_apart() { + // (destination, source, bytes) + assert!(continues((1000, 5000, 16), (1016, 5016, 32))); + assert!(continues((5000, 1000, 16), (5016, 1016, 32))); + // A gap, or only one side continues. + assert!(!continues((1000, 5000, 16), (1020, 5016, 32))); + assert!(!continues((1000, 5000, 16), (1016, 5020, 32))); + assert!(!continues((1000, 5000, 16), (1000, 5000, 16))); + // Together they would overlap: the second reads what the first wrote. + assert!(!continues((1000, 1016, 16), (1016, 1032, 16))); + assert!(!continues((1016, 1000, 16), (1032, 1016, 16))); + // They touch without overlapping. + assert!(continues((1000, 1032, 16), (1016, 1048, 16))); + assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8))); + } + + /// Ranges are found by what they hold, not by where they start, and a + /// range that only touches another's end does not touch it. + #[test] + fn ranges_touch_where_they_overlap() { + let mut ranges = Vec::new(); + join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]); + assert_eq!(ranges, [(10, 25), (40, 60)]); + join_ranges(&mut ranges, [(25, 40)]); + assert_eq!(ranges, [(10, 60)]); + let ranges = [(10usize, 25usize), (40, 60), (100, 101)]; + for (from, to, hit) in [ + (0, 10, false), + (0, 11, true), + (24, 25, true), + (25, 40, false), + (25, 41, true), + (59, 200, true), + (60, 100, false), + (100, 101, true), + (101, 500, false), + (30, 30, false), + (50, 50, false), + ] { + assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}"); + } + assert!(!touches(&[], 0, usize::MAX)); + } +} + +/// Whether a title buffer copy that continues the one recorded before it +/// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by +/// default). +/// +/// Each copy is done at submission through the kernel, which reports a +/// page that is not there instead of faulting (`copy_mapped`), tells the +/// write watch and the guards, and ends the refreshes gathered so far: a +/// call into the kernel for some 480 bytes, 14,042 times a frame in run 86 +/// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them +/// continue the one before is counted either way and said on its own line +/// with the frame rate; the switch is worth that many kernel calls. +/// +/// Joined, the same bytes move: [`continues`] joins only copies whose +/// ranges, taken together, do not overlap, and nothing is recorded between +/// two steps that follow each other. What differs: a page that is not +/// mapped now fails the joined copy as a whole (it then goes page by page, +/// zeros for what cannot be read, as a single copy does), where before +/// only the copy that held it did. +fn join_copies() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1")) +} + +/// Since the last frame-rate line: title buffer copies recorded, and those +/// that continue the one before ([`join_copies`]). +static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether the copy `next` (destination, source, bytes) goes on exactly +/// where `last` ended, source and destination both, and the two as one do +/// not overlap (source over destination): then one copy of both moves the +/// bytes the two would move in turn. +fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool { + let ((d, s, n), (dst, src, len)) = (last, next); + let Some(all) = n.checked_add(len) else { + return false; + }; + d.checked_add(n) == Some(dst) + && s.checked_add(n) == Some(src) + && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d)) +} + +/// The ranges the shaders of `runs` may write, per host copy, as declared. +/// One list's lock at a time: a submission may name a list twice. +fn declared_writes(runs: &[&HostList]) -> Vec { + let mut back: Vec = Vec::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::GpuWrite(shadow, address, len) = step { + let range = (*address, *address + *len); + match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, ranges)) => { + if !ranges.contains(&range) { + ranges.push(range); + } + } + None => back.push((shadow.clone(), vec![range])), + } + } + } + } + back +} + +/// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log +/// lines that say what the title's CPU was given while it decided whether +/// the camera is in a room. The values of the small read-backs +/// ([`read_backs`]), the frame's main pass by scissor rectangle with its +/// culling dispatches (`draw.rs`, `walls_census`), the shader-written +/// buffers merged into title memory (`shadow.rs`, `walls_merged`), host +/// copies found stale after their refresh (`shadow.rs`), and, in the +/// runtime, the read requests that fail (with 2: every request). +pub(crate) fn walls_trace() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2")) +} + +/// After `list` has run: the texels its read-backs copied into host +/// buffers of ours go to the title's memory (`HostList::defer_read_back`). +/// +/// A submission that is waited for did this itself. One sent ahead +/// ([`late`]) did not, at any stage: the flights' lists were settled +/// without it, so the title read a buffer nobody wrote, as before read-backs +/// were made (the exposure metering's two small float targets, every frame). +fn read_backs(list: &HostList) { + for (buffer, at, [row, rows, pitch]) in &list.deferred().backs { + let mut data = std::ptr::null_mut(); + // SAFETY: a read-back buffer of ours, written by the list that has + // run; the title's destination holds every row (checked when the + // copy was recorded). + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() { + let from = data.cast::().cast_const(); + for line in 0..*rows { + std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row); + } + // The walls trace: what the title is handed (one row of at + // most 24 values: its 5x1 and 1x1 float targets). + if walls_trace() && *rows == 1 && *row <= 96 { + let mut values = [0f32; 24]; + std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::(), *row & !3); + tracing::info!( + frame = crate::frame::current(), + to = format_args!("{:#x}", *at), + bytes = *row, + values = ?&values[..*row / 4], + "walls trace: a read-back lands in title memory" + ); + } + buffer.Unmap(0, None); + } + } + } +} + +/// After the card ran what declared `back`: what shaders wrote there goes +/// into title memory, and the ranges are done with. +fn hand_back(back: &[Declared]) { + if crate::shadow::wide_back() { + // Every range first (the pieces that differ, found on several + // threads), then the merges, in order, as below. + let mut work: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); + for (shadow, declared) in back { + if shadow.carded() { + continue; + } + let mut sorted = declared.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to))); + } + #[cfg(feature = "diagnostics")] + let scanning = std::time::Instant::now(); + let found = crate::shadow::find_all(&work); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); + for ((shadow, from, to), found) in work.iter().zip(found) { + let written = shadow.copy_back_with(*from, to - from, Some(found)); + COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(*from, to - from, written); + } + for (shadow, declared) in back { + shadow.copy_back_done(declared); + } + return; + } + for (shadow, declared) in back { + if shadow.carded() { + // Done before (`Host::card_back`). + shadow.copy_back_done(declared); + continue; + } + // Each byte compared once: the world declares dozens of views + // of its 174 MB heap that overlap almost entirely, and comparing + // every one whole was gigabytes a frame (0.3-0.5 s) for the few + // MB shaders wrote. Only ranges that overlap or touch are + // joined: what lies between two was not given to shaders (the + // snapshot does not hold it). + let mut sorted = declared.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + for (from, to) in spans { + let written = shadow.copy_back(from, to - from); + COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(from, to - from, written); + } + shadow.copy_back_done(declared); + } +} + +impl Host { + /// Whether the host runs mesh shaders at shader model 6.6 (translated + /// mesh shaders need both); logged once. + pub(crate) fn mesh_shaders(&self) -> bool { + static MESH: OnceLock = OnceLock::new(); + *MESH.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, }; // SAFETY: each query writes its own structure of the given size. - let (opt_ok, sm_ok) = unsafe { - ( - self.device - .CheckFeatureSupport( - D3D12_FEATURE_D3D12_OPTIONS7, - (&raw mut options).cast(), - size_of_val(&options) as u32, - ) - .is_ok(), - self.device + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + && self + .device .CheckFeatureSupport( D3D12_FEATURE_SHADER_MODEL, (&raw mut model).cast(), size_of_val(&model) as u32, ) - .is_ok(), - ) + .is_ok() + }; + let mesh = ok + && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED + && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; + tracing::info!(mesh, "host mesh shader support"); + mesh + }) + } + + /// Whether the host GPU supports the depth bounds test; logged once. + pub(crate) fn depth_bounds(&self) -> bool { + static BOUNDS: OnceLock = OnceLock::new(); + *BOUNDS.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default(); + // SAFETY: writes `options` of the given size. + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS2, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + }; + let supported = ok && options.DepthBoundsTestSupported.as_bool(); + tracing::info!(supported, "host depth bounds support"); + supported + }) + } + + /// A new list, open for recording. + pub(crate) fn new_list(&self) -> windows::core::Result { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + let before = private_bytes(); + let list = self.make_list(); + LISTS[0].fetch_add(1, Ordering::Relaxed); + // (May shrink while a list is made, on another thread's account: + // added as it is, the sum is what counts.) + #[cfg(feature = "diagnostics")] + LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::HostLists, 1); + add(C::HostListNs, started.elapsed().as_nanos() as u64); + } + list + } + + /// An allocator and a closed list for a prelude. + fn make_prelude(&self) -> Option { + // SAFETY: plain object creation. + let made: windows::core::Result = unsafe { + (|| { + let allocator: ID3D12CommandAllocator = + self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = + self.device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.Close()?; + Ok((allocator, list)) + })() + }; + LISTS[1].fetch_add(1, Ordering::Relaxed); + match made { + Ok(prelude) => Some(prelude), + Err(e) => { + tracing::warn!(error = %e, "no host list for a prelude"); + None + } + } + } + + fn make_list(&self) -> windows::core::Result { + // SAFETY: plain object creation. + unsafe { + let allocator: ID3D12CommandAllocator = self + .device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = self.device.CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT, + &allocator, + None, + )?; + let prelude = OnceLock::new(); + if !lazy_prelude() { + let _ = prelude.set(self.make_prelude()); + } + Ok(HostList { + allocator, + list, + deferred: Mutex::default(), + scratch: Mutex::default(), + states: Mutex::default(), + twins: Mutex::default(), + prelude, + pipelines: Mutex::default(), + budget: OnceLock::new(), + indirect_args: Mutex::default(), + _alive: Counted::new(), + #[cfg(feature = "diagnostics")] + notes: Mutex::default(), + #[cfg(feature = "diagnostics")] + stamps: OnceLock::new(), + }) + } + } + + /// The card's clock ([`CARD_CLOCK_US`]), made at the first send. + fn card_clock(&self) -> Option<&'static CardClock> { + static CLOCK: OnceLock> = OnceLock::new(); + static WATCH: std::sync::Once = std::sync::Once::new(); + let clock = CLOCK + .get_or_init(|| { + // SAFETY: a plain fence on our device. + let fence = unsafe { self.device.CreateFence::(0, D3D12_FENCE_FLAG_NONE) }.ok()?; + Some(CardClock { + fence, + state: Mutex::new((0, None)), + sent: std::sync::Condvar::new(), + }) + }) + .as_ref()?; + WATCH.call_once(|| { + if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) { + tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0"); + } + }); + Some(clock) + } + + /// Lists of ours just went to the queue: the clock's signal goes + /// behind them, and an idle stretch of the card, if one was under way, + /// ends here ([`CARD_CLOCK_US`]). + fn card_sent(&self) { + let Some(clock) = self.card_clock() else { + return; + }; + let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); + state.0 += 1; + // SAFETY: our queue and the clock's fence. + let _ = unsafe { self.queue.Signal(&clock.fence, state.0) }; + if let Some((since, worked_then)) = state.1.take() { + CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed); + CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed); + } + drop(state); + clock.sent.notify_one(); + } + + /// Whether the host has what copies in the card's memory need (three + /// lists and the compare); made at the first ask. A copy goes to the + /// card's memory only if it has. + pub(crate) fn card_ready(&self) -> bool { + static READY: OnceLock = OnceLock::new(); + *READY.get_or_init(|| match self.make_card_work() { + Ok(work) => { + *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work); + true + } + Err(e) => { + tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made"); + false + } + }) + } + + fn make_card_work(&self) -> windows::core::Result { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option = None; + // SAFETY: the source and names live through the call; the out + // pointer is ours. + unsafe { + D3DCompile( + CARD_COMPARE.as_ptr().cast(), + CARD_COMPARE.len(), + windows::core::s!("card compare"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + } + let code = code.ok_or_else(windows::core::Error::empty)?; + let list = || self.make_prelude().ok_or_else(windows::core::Error::empty); + // A megabyte of results: 262,144 pieces, 16 GB of declared ranges + // in one submission. + const RESULTS: u64 = 1 << 20; + let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?; + name(&differs, || "card compare results".into()); + // SAFETY: the blob's own bytes; the root signature is inside the + // shader. + unsafe { + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok(CardWork { + sync: vec![list()?], + check: vec![list()?], + fetch: list()?, + root, + pso, + differs: (differs, data as usize, RESULTS), + fetched: None, + taken: 0, + out: 0, + }) + } + } + + /// Before a submission's lists run, for copies in the card's memory + /// ([`crate::shadow::cards`]): what changed on their CPU side since + /// the last submission goes to their card side (a list of ours, run + /// now; the submission's lists follow it on the queue), and the ranges + /// this submission's shaders may write get a compare to run after its + /// lists. `None` if there is nothing to do. + /// + /// `flown`: the submission is sent ahead with [`relay`]. Its compare + /// then stores the hashes it makes (see [`flagged_pieces`] and + /// `relay`). + fn card_before(&self, runs: &[&HostList], flown: bool) -> Option { + use std::sync::Arc; + if !crate::shadow::cards() { + return None; + } + // The ranges this submission's shaders may write, per copy. + let mut declared: Vec<(Arc, Vec<(usize, usize)>)> = Vec::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::GpuWrite(shadow, address, len) = step + && shadow.carded() + { + let range = (*address, *address + *len); + match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) { + Some((_, ranges)) => { + if !ranges.contains(&range) { + ranges.push(range); + } + } + None => declared.push((shadow.clone(), vec![range])), + } + } + } + } + // With the relay: the order of the queue is held from here until + // what is taken is on the queue, and the taking is numbered. + let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); + let sent_as = match order.as_mut() { + Some(order) => { + **order += 1; + **order + } + None => 0, + }; + let mut dirty = crate::shadow::card_dirty(sent_as); + if declared.is_empty() && dirty.is_empty() { + return None; + } + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let work = work.as_mut()?; + // A copy whose shader writes are declared for the first time gets + // its bytes from before, whole. + let mut whole: Vec> = Vec::new(); + for (shadow, _) in &declared { + if shadow.card_make_before(|size| { + let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?; + name(&before, || "title buffer on the card, hashes of its pieces".into()); + Some(before) + }) { + whole.push(shadow.clone()); + if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) { + dirty.push((shadow.clone(), Vec::new())); + } + } + } + let mut used: Vec<(bool, Prelude)> = Vec::new(); + if !dirty.is_empty() { + let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else { + fail(format_args!("no host list to bring host copies in the card's memory up to date")); + }; + let (allocator, list) = &sync; + // SAFETY: the list's last run finished (it ran ahead of a + // submission that was waited for, and came back after that); + // live buffers, and the ranges lie in them. + let recorded = unsafe { + (|| -> windows::core::Result<()> { + allocator.Reset()?; + list.Reset(allocator, None)?; + for (shadow, ranges) in &dirty { + let Some((staging, before, size)) = shadow.card_sides() else { + continue; + }; + for &(a, b) in ranges { + list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64); + crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed); + } + crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed); + let Some(before) = before else { + continue; + }; + // No twin (it cost the card the copy's size again, + // 399 MB in run 75): `before` holds a 128-bit hash + // of each 64 KiB piece. The pieces just sent up are + // hashed again, all of them the first time; the + // compare after the lists hashes the declared + // pieces and flags those whose hash is another. + if !ranges.is_empty() { + list.ResourceBarrier(&[transition( + &shadow.buffer, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + list.SetComputeRootSignature(&work.root); + list.SetPipelineState(&work.pso); + list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + let runs: Vec = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) { + vec![shadow.card_run(0, usize::MAX)] + } else { + ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect() + }; + // The same pieces in fewer passes (`rehash_runs`). + let runs = if rehash_runs() { crate::shadow::joined_piece_runs(runs) } else { runs }; + CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); + CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::(), Ordering::Relaxed); + for run in runs { + let constants = [run.first, run.skew, size as u32, run.pieces, 0, 0]; + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.Dispatch(run.pieces.div_ceil(64), 1, 1); + } + } + list.Close()?; + self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); + Ok(()) + })() + }; + if let Err(e) = recorded { + fail(format_args!("host copies in the card's memory could not be brought up to date ({e})")); + } + used.push((false, sync)); + } + drop(order); + let mut plan = CardPlan { + ranges: Vec::new(), + check: None, + _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(), + lists: used, + }; + // Each byte once, as the copy-back joins the declared ranges. The + // results go behind those of plans still in the air. + let mut at = work.taken; + for (shadow, ranges) in &declared { + let mut sorted = ranges.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + for (from, to) in spans { + let Some(span) = shadow.card_span(from, to) else { + continue; + }; + let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2; + plan.ranges.push(CardRange { + shadow: shadow.clone(), + declared: (from, to), + span, + at, + compared, + }); + if compared { + at += span.pieces; + } + } + } + work.taken = at; + if plan.ranges.iter().any(|r| r.compared) { + let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else { + fail(format_args!("no host list for the compare of host copies in the card's memory")); + }; + let (allocator, list) = ✓ + // SAFETY: the list's last run finished (its submission was + // waited for, and it came back after that); live buffers; the + // compare's own root signature. + let recorded = unsafe { + (|| -> windows::core::Result { + allocator.Reset()?; + list.Reset(allocator, None)?; + // What the submission's shaders wrote, first. + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + list.SetComputeRootSignature(&work.root); + list.SetPipelineState(&work.pso); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + for r in plan.ranges.iter().filter(|r| r.compared) { + let Some((_, Some(before), size)) = r.shadow.card_sides() else { + continue; + }; + let constants = [r.span.first, r.span.skew, size as u32, r.span.pieces, r.at * 4, if flown { 2 } else { 1 }]; + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); + list.Dispatch(r.span.pieces.div_ceil(64), 1, 1); + CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); + } + list.Close()?; + list.cast() + })() + }; + match recorded { + Ok(list) => plan.check = Some(list), + Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")), + } + plan.lists.push((true, check)); + } + work.out += 1; + Some(plan) + } + + /// With [`relay`]: whether the compare's result area is half taken by + /// plans in the air. It starts from the beginning only when no plan is + /// out, so the caller lets the flights land first. + fn card_results_low(&self) -> bool { + CARD_WORK + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2) + } + + /// The plan's submission has run and its results were read + /// ([`Host::card_back`]): its lists are free for the next plan. Called + /// when nothing of ours is on the card, so the compare's results start + /// from the beginning again. + fn card_done(&self, plan: CardPlan) { + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_mut() else { + return; + }; + for (check, list) in plan.lists { + if check { work.check.push(list) } else { work.sync.push(list) } + } + work.out = work.out.saturating_sub(1); + // With the relay other plans may be on the card, their results + // not read yet: the area starts again only when none is out. + if !relay() || work.out == 0 { + work.taken = 0; + } + } + + /// The relay's own list, fence, event for [`Host::relay_card_back`]. + fn make_relay_fetch(&self) -> Option { + let list = self.make_prelude()?; + // SAFETY: plain objects of our own. + unsafe { + let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + Some(RelayFetch { + list, + fence, + event, + sent: 0, + buffer: None, + }) + } + } + + /// [`relay`], on the thread that lands flights: for the plans of the + /// flights being landed (the card has run them), the pieces their + /// compares flagged are fetched, once each, with a list and a wait of + /// this thread's own, and what shaders wrote in them goes into title + /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but: + /// no submission lock; a piece flagged under one range of a plan is + /// fetched under all ([`flagged_pieces`]); the fetch runs behind + /// whatever was sent meanwhile, so it may bring a later flight's + /// bytes, which that flight's landing then finds merged already; and + /// nothing is sent back up. + fn relay_card_back(&self, plans: &[&CardPlan], fetch: &mut Option) { + let differs = { + let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize)) + }; + let mut pieces: Vec<(std::sync::Arc, usize, usize, u64)> = Vec::new(); + let mut total = 0u64; + if let Some((differs, dwords)) = differs { + // SAFETY: the mapping of the results. The compares of these + // plans have run, and their dwords are given to no other plan + // before these are done with (`card_done`). + let differs = unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) }; + let mut seen = std::collections::HashSet::new(); + for plan in plans { + let flags: Vec<(usize, u32, bool)> = plan + .ranges + .iter() + .flat_map(|r| { + (0..r.span.pieces).map(move |p| { + let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| d != 0); + (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, flagged) + }) + }) + .collect(); + let fetched = flagged_pieces(&flags); + for r in &plan.ranges { + let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; + for p in 0..r.span.pieces { + if !fetched.contains(&(copy, r.span.first + p)) { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + if lo < hi && seen.insert((copy, lo, hi)) { + pieces.push((r.shadow.clone(), lo, hi, total)); + total += (hi - lo) as u64; + } + } + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + } + } + } + if pieces.is_empty() { + // Nothing to fetch: every send so far is older than the next fetch. + crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); + return; + } + if fetch.is_none() { + *fetch = self.make_relay_fetch(); + } + let Some(f) = fetch.as_mut() else { + fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)")); + }; + if f.buffer.as_ref().is_none_or(|b| b.2 < total) { + let size = total.next_multiple_of(16 << 20); + f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); + } + let Some((buffer, data, _)) = f.buffer.clone() else { + fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)")); + }; + f.sent += 1; + let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent); + let waiting = std::time::Instant::now(); + // SAFETY: the list's last run was waited for by this thread; live + // buffers (the copies are held by the plans); the fence and the + // event are this thread's. + let ran = unsafe { + (|| -> windows::core::Result { + allocator.Reset()?; + list.Reset(&allocator, None)?; + for (shadow, lo, hi, at) in &pieces { + list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64); + } + list.Close()?; + let lists = [Some(list.cast::()?)]; + // In the order of the queue: the sends of title bytes so + // far are ahead of this fetch, every later one behind it. + let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()); + self.queue.ExecuteCommandLists(&lists); + let after = *order; + drop(order); + self.card_sent(); + self.queue.Signal(&fence, sent)?; + fence.SetEventOnCompletion(sent, event)?; + WaitForSingleObject(event, INFINITE); + Ok(after) + })() + }; + let after = match ran { + Ok(after) => after, + Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")), + }; + let us = waiting.elapsed().as_micros() as u64; + RELAY_STATS[3].fetch_add(us, Ordering::Relaxed); + { + use crate::shadow::CARD_STATS; + CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed); + CARD_STATS[4].fetch_add(total, Ordering::Relaxed); + CARD_STATS[5].fetch_add(1, Ordering::Relaxed); + CARD_STATS[6].fetch_add(us, Ordering::Relaxed); + } + let mut title = Vec::new(); + let mut written = 0; + for (shadow, lo, hi, at) in &pieces { + // SAFETY: the mapping of the fetched bytes, `total` of them; + // the copy into it has run. + let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) }; + let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title); + shadow.walls_merged(gpu.len(), merged); + written += merged; + } + COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + // Sends up to `after` are of no use to any later merge. + crate::shadow::relay_fetched(after); + } + + /// [`relay`], on the thread that lands flights: `items` are the first + /// things of the line, flights the card has run and what follows them. + /// What their shaders wrote goes into title memory (copies in the + /// card's memory first, then the others, each byte once whichever + /// flights declared it); then every flight's ranges are done with; + /// then, in the line's order, each flight's read-backs, its + /// bottom-of-pipe writes and the fence signals behind it. Title memory + /// is complete before the title is told anything. + fn relay_land(&self, items: Vec, fetch: &mut Option) { + let landing = std::time::Instant::now(); + { + let flights: Vec<&Flight> = items + .iter() + .filter_map(|l| match l { + Late::Run(flight) => Some(flight), + _ => None, + }) + .collect(); + if !flights.is_empty() { + // SAFETY: a plain query. + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect(); + fail(format_args!( + "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}", + flights.len(), + runs.len(), + self.removal_data(&runs), + last_notes(&runs) + )); + } + let plans: Vec<&CardPlan> = flights.iter().filter_map(|f| f.card.as_ref()).collect(); + self.relay_card_back(&plans, fetch); + let mut back: Vec = Vec::new(); + for flight in &flights { + for (shadow, ranges) in &flight.back { + match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, all)) => { + for range in ranges { + if !all.contains(range) { + all.push(*range); + } + } + } + None => back.push((shadow.clone(), ranges.clone())), + } + } + } + relay_hand_back(&back); + // Only now, and flight by flight: a range another flight + // in the air declared too stays closed to refreshes. + for flight in &flights { + for (shadow, ranges) in &flight.back { + shadow.copy_back_done(ranges); + } + } + COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); + RELAY_STATS[0].fetch_add(1, Ordering::Relaxed); + RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed); + } + } + // In the order given: what tells the title the card is done. + let mut last = 0; + let mut landed = Vec::new(); + for item in items { + match item { + Late::Run(flight) => { + last = flight.number; + for &i in &flight.order { + read_backs(flight.lists[i].host()); + } + if let Some(card) = flight.card { + self.card_done(card); + } + landed.push((flight.lists, flight.order)); + } + Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), + Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value), + } + } + if last > 0 { + FINISHED.store(last, Ordering::Release); + bury(last); + } + self.log_messages(); + RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); + { + let mut line = line(); + let Line { + line: items, + written, + lists, + settling, + poke, + landed: kept, + in_hand, + .. + } = &mut *line; + kept.extend(landed); + in_hand.clear(); + // What is still in the air, from the flights that are. + written.clear(); + *lists = 0; + let mut ranges = Vec::new(); + for item in items.iter() { + if let Late::Run(flight) = item { + *lists += flight.order.len().max(1); + ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied())); + } + } + join_ranges(written, ranges); + *settling = false; + // The landed lists are reset, and what queues hold looked at, + // by the helper thread (they take locks a waiter may hold). + *poke = true; + } + LINE_MOVED.notify_all(); + LINE_LANDED.notify_all(); + } + + /// After a submission ran, for copies in the card's memory: the pieces + /// of the declared ranges that the compare found differing (all of a + /// range it did not compare) are fetched, with one more wait for the + /// card, and what shaders wrote in them goes into title memory. + /// `submitted` is the last value signalled on the fence. `seen` holds + /// the pieces fetched already since the card was last waited for + /// (several submissions settled together name the same ones). + fn card_back( + &self, + plan: &CardPlan, + submitted: &mut u64, + seen: &mut std::collections::HashSet<(usize, usize, usize)>, + ) { + if plan.ranges.is_empty() { + return; + } + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_mut() else { + return; + }; + // SAFETY: the mapping of the results, which the compare (it has + // run) wrote. + let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) }; + // The pieces to fetch: the range, the offsets in its copy, and + // where the bytes come down. + let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new(); + let mut total = 0u64; + for (i, r) in plan.ranges.iter().enumerate() { + for p in 0..r.span.pieces { + if r.compared && differs[(r.at + p) as usize] == 0 { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) { + pieces.push((i, lo, hi, total)); + total += (hi - lo) as u64; + } + } + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + } + let mut written = vec![0usize; plan.ranges.len()]; + if !pieces.is_empty() { + if work.fetched.as_ref().is_none_or(|f| f.2 < total) { + let size = total.next_multiple_of(16 << 20); + work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); + } + let Some((fetched, data, _)) = &work.fetched else { + fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)")); + }; + let waiting = std::time::Instant::now(); + let (allocator, list) = &work.fetch; + // SAFETY: the list's last run was waited for; live buffers; the + // fence and event are ours, under the submission lock. + let ran = unsafe { + (|| -> windows::core::Result<()> { + allocator.Reset()?; + list.Reset(allocator, None)?; + for &(i, lo, hi, at) in &pieces { + list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64); + } + list.Close()?; + self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); + self.card_sent(); + *submitted += 1; + self.queue.Signal(&self.fence, *submitted)?; + self.fence.SetEventOnCompletion(*submitted, self.event)?; + let was_working = working(false); + WaitForSingleObject(self.event, INFINITE); + stood(waiting); + working(was_working); + Ok(()) + })() + }; + if let Err(e) = ran { + fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})")); + } + { + use crate::shadow::CARD_STATS; + CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed); + CARD_STATS[4].fetch_add(total, Ordering::Relaxed); + CARD_STATS[5].fetch_add(1, Ordering::Relaxed); + CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + } + if wide_merge() && pieces.len() >= 8 { + // The pieces are apart from one another (each its own bytes + // of its copy and of title memory): several at a time. + let fetched = *data; + let counts: std::sync::Arc> = + std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect()); + let each = pieces.len().div_ceil(8); + let jobs: Vec> = pieces + .chunks(each) + .map(|chunk| { + let chunk: Vec<(std::sync::Arc, usize, usize, usize, u64)> = + chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect(); + let counts = counts.clone(); + Box::new(move || { + let mut title = Vec::new(); + for (shadow, i, lo, hi, at) in chunk { + // SAFETY: the mapping of the fetched bytes; + // the copy into it has run, and the caller + // waits for this job. + let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) }; + let merged = shadow.card_merge(lo, gpu, &mut title); + shadow.walls_merged(gpu.len(), merged); + counts[i].fetch_add(merged, Ordering::Relaxed); + } + }) as Box + }) + .collect(); + crate::shadow::wide_run(jobs); + for (written, count) in written.iter_mut().zip(counts.iter()) { + *written += count.load(Ordering::Relaxed); + } + } else { + let mut title = Vec::new(); + for &(i, lo, hi, at) in &pieces { + // SAFETY: the mapping of the fetched bytes, `total` of + // them; the copy into it has run. + let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) }; + let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title); + plan.ranges[i].shadow.walls_merged(gpu.len(), merged); + written[i] += merged; + } + } + } + for (r, written) in plan.ranges.iter().zip(written) { + COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + let (from, to) = r.declared; + #[cfg(feature = "diagnostics")] + crate::copystat::compared(from, to - from, written); + let _ = (from, to); + } + } + + /// Runs closed lists and waits for them, and with [`late`] for + /// everything sent to the card before them, which is settled first. + pub(crate) fn execute(&self, runs: &[&HostList]) { + let _ = self.submit(runs, false); + } + + /// A queue's submission with [`late`]: the host lists `lists`, taken + /// from the title's, go to the card in `order` and are not waited for. + /// They join the line of flights and are settled, with the others in + /// the air, at the next point where what they do can be observed + /// ([`late`] lists those points); their host lists are reset and kept + /// for reuse then, as a queue does for the lists it ran. + pub(crate) fn execute_late(&self, lists: Vec, order: Vec) { + if order.is_empty() { + crate::list::recycle(lists, &order); + return; + } + late_threads(); + let sent = { + let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect(); + self.submit(&runs, true) + }; + let Some((mut submitted, sent)) = sent else { + // (Not reached: a submission sent ahead always comes back.) + crate::list::recycle(lists, &order); + return; + }; + let told = !sent.writes.is_empty(); + let most = { + let mut line = line(); + let Line { line: items, written, lists: flying, target, .. } = &mut *line; + join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied())); + *flying += order.len(); + *target = *submitted; + items.push(Late::Run(Flight { + number: sent.number, + fence: *target, + lists, + order, + card: sent.card, + back: sent.back, + })); + items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); + *flying >= late_most() + }; + LATE_STATS[0].fetch_add(1, Ordering::Relaxed); + RELAY_MOVED.notify_one(); + if told && !late_writes() { + self.settle(&mut submitted, WHY_WRITES); + } else if most && relay_exact() { + // Until there are fewer, not until there are none. + relay_wait(WHY_MOST, |line| line.lists < late_most()); + } else if most { + self.settle(&mut submitted, WHY_MOST); + } else { + LINE_MOVED.notify_one(); + } + drop(submitted); + land(); + } + + /// Sends `list`, a closed list of ours (the present's copy), as a + /// flight ([`late_free_present`]): not waited for, settled with the + /// others. The caller keeps the list and does not reset it before the + /// submission whose number comes back has finished ([`FINISHED`]); 0 if + /// it ran and was waited for after all. + fn execute_own(&self, list: &HostList) -> u64 { + late_threads(); + let Some((submitted, sent)) = self.submit(&[list], true) else { + return 0; + }; + let number = sent.number; + { + let mut line = line(); + let Line { line: items, written, lists: flying, target, .. } = &mut *line; + join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied())); + *flying += 1; + *target = *submitted; + items.push(Late::Run(Flight { + number, + fence: *target, + lists: Vec::new(), + order: Vec::new(), + card: sent.card, + back: sent.back, + })); + items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); + } + LATE_STATS[0].fetch_add(1, Ordering::Relaxed); + LINE_MOVED.notify_one(); + RELAY_MOVED.notify_one(); + drop(submitted); + number + } + + /// Waits for the card to run every flight in the air ([`late`]) and + /// does what they left to do, as [`Host::execute`] does for one + /// submission after its wait: the pieces their shaders wrote in copies + /// in the card's memory are fetched and merged (each once), the ranges + /// they declared in the other copies are compared and copied back + /// (each byte once, whichever flights declared it), and then, in the + /// order they were given: their bottom-of-pipe writes and the fence + /// signals behind them. `submitted` is the submission lock's value; + /// `why` one of the `WHY_` places. Nothing happens if nothing flies. + /// + /// Everything in the air is settled, never the first flights alone: + /// the merge writes the copies' CPU side, which a flight still on the + /// card may be writing too. + fn settle(&self, submitted: &mut u64, why: usize) { + if !late() { + return; + } + if relay() { + // Nothing is settled here: the thread that lands flights does + // it, in order, and this waits until nothing is in the air and + // nothing is being landed. Every point that settled before + // comes here, so each still sees title memory, fences and + // bottom-of-pipe values as after a settle. + relay_wait(why, |line| line.line.is_empty() && !line.settling); + return; + } + let was_working = working(true); + let mut counted = false; + loop { + let items = { + let mut line = line(); + if line.line.is_empty() { + line.settling = false; + break; + } + line.settling = true; + line.written.clear(); + line.lists = 0; + std::mem::take(&mut line.line) }; - let sm66 = sm_ok && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; - let hardware = opt_ok && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED; - let override_env = std::env::var("VICTORY_MESH_EMULATION").ok(); - let mode = match override_env.as_deref().map(str::trim) { - Some(v) if v == "1" || v.eq_ignore_ascii_case("true") => { - if sm66 { - MeshSupport::Emulate - } else { - MeshSupport::Unsupported + let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count(); + if !counted { + counted = true; + LATE_STATS[1].fetch_add(1, Ordering::Relaxed); + LATE_STATS[why].fetch_add(1, Ordering::Relaxed); + } + LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed); + if flights > 0 { + submitting(2, flights); + let waiting = std::time::Instant::now(); + // SAFETY: the fence and event are ours, under the + // submission lock; `submitted` is the last value signalled. + unsafe { + match self.fence.SetEventOnCompletion(*submitted, self.event) { + Ok(()) => { + working(false); + WaitForSingleObject(self.event, INFINITE); + stood(waiting); + working(true); + } + Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"), + } + } + let gpu = waiting.elapsed(); + LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::card_waited(gpu.as_micros() as u64, || { + format!("{flights} submissions sent ahead, settled together") + }); + // SAFETY: a plain query. + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + let runs: Vec<&HostList> = items + .iter() + .filter_map(|i| match i { + Late::Run(f) => Some(f), + _ => None, + }) + .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())) + .collect(); + fail(format_args!( + "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}", + runs.len(), + self.removal_data(&runs), + last_notes(&runs) + )); + } + submitting(3, flights); + let copying = std::time::Instant::now(); + let mut seen = std::collections::HashSet::new(); + let mut back: Vec = Vec::new(); + for item in &items { + let Late::Run(flight) = item else { + continue; + }; + if let Some(card) = &flight.card { + self.card_back(card, submitted, &mut seen); + } + for (shadow, ranges) in &flight.back { + match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, all)) => { + for range in ranges { + if !all.contains(range) { + all.push(*range); + } + } + } + None => back.push((shadow.clone(), ranges.clone())), + } } } - Some(v) if v == "0" || v.eq_ignore_ascii_case("false") => { - if sm66 && hardware { - MeshSupport::Native - } else { - MeshSupport::Unsupported + hand_back(&back); + COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed); + } + // In the order given: what tells the title the card is done. + let mut last = 0; + let mut landed = Vec::new(); + for item in items { + match item { + Late::Run(flight) => { + last = flight.number; + for &i in &flight.order { + read_backs(flight.lists[i].host()); + } + if let Some(card) = flight.card { + self.card_done(card); + } + landed.push((flight.lists, flight.order)); } + Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), + Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value), } - _ if !sm66 => MeshSupport::Unsupported, - _ if hardware => MeshSupport::Native, - _ => MeshSupport::Emulate, - }; - tracing::info!(?mode, sm66, hardware, "host mesh shader support"); - mode - }) - } - - /// Whether the host runs native mesh shaders at shader model 6.6. - pub(crate) fn mesh_shaders(&self) -> bool { - self.mesh_support() == MeshSupport::Native - } - - /// Whether mesh shaders run as compute plus generated vertex shaders. - pub(crate) fn emulate_mesh_shaders(&self) -> bool { - self.mesh_support() == MeshSupport::Emulate - } - - /// Whether the host GPU supports the depth bounds test; logged once. - pub(crate) fn depth_bounds(&self) -> bool { - static BOUNDS: OnceLock = OnceLock::new(); - *BOUNDS.get_or_init(|| { - let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default(); - // SAFETY: writes `options` of the given size. - let ok = unsafe { - self.device - .CheckFeatureSupport( - D3D12_FEATURE_D3D12_OPTIONS2, - (&raw mut options).cast(), - size_of_val(&options) as u32, - ) - .is_ok() - }; - let bounds = ok && options.DepthBoundsTestSupported.as_bool(); - tracing::info!(bounds, "host depth bounds test support"); - bounds - }) - } - - /// A new list, open for recording. - pub(crate) fn new_list(&self) -> windows::core::Result { - // SAFETY: plain object creation. - unsafe { - let allocator: ID3D12CommandAllocator = self - .device - .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list: ID3D12GraphicsCommandList = self.device.CreateCommandList( - 0, - D3D12_COMMAND_LIST_TYPE_DIRECT, - &allocator, - None, - )?; - let prelude_allocator: ID3D12CommandAllocator = self - .device - .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let prelude: ID3D12GraphicsCommandList = self.device.CreateCommandList( - 0, - D3D12_COMMAND_LIST_TYPE_DIRECT, - &prelude_allocator, - None, - )?; - prelude.Close()?; - Ok(HostList { - allocator, - list, - deferred: Mutex::default(), - scratch: Mutex::default(), - states: Mutex::default(), - shadow_states: Mutex::default(), - pending_barriers: Mutex::default(), - closed: AtomicBool::new(false), - prelude: (prelude_allocator, prelude), - pipelines: Mutex::default(), - budget: OnceLock::new(), - #[cfg(feature = "diagnostics")] - notes: Mutex::default(), - #[cfg(feature = "diagnostics")] - stamps: OnceLock::new(), - }) + } + if last > 0 { + FINISHED.store(last, Ordering::Release); + bury(last); + } + line().landed.extend(landed); + } + if counted { + self.log_messages(); + submitting(0, 0); + // What was settled may be what a queue stands at, and the + // caller may not be one that looks (a read-back, a present). + if why != WHY_CARD_DONE { + line().poke = true; + LINE_MOVED.notify_one(); + } } + working(was_working); } - /// Runs closed lists in order and waits for each before preparing the next. - pub(crate) fn execute(&self, runs: &[&HostList]) { + /// [`Host::execute`], or with `late` the first half of + /// [`Host::execute_late`]: the lists are prepared and sent, and what is + /// to be done once they have run comes back with the submission lock + /// still held. + fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> { + #[cfg(feature = "diagnostics")] + let called = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + crate::copystat::submission_begins(); // One submission at a time from preparation to copy-back: snapshots // and the ranges shaders write are per host copy, not per submission. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); - crate::breadcrumb::clear(); - self.submit(&mut submitted, runs); - } - - /// Runs a title's submission: as [`execute`](Self::execute), but first, - /// under the same lock, starts a new watch submission and refreshes heap - /// slots the title wrote. Inside the lock, another queue's submission - /// can't refresh a heap while this one's GPU work still reads it. - pub(crate) fn execute_title(&self, runs: &[&HostList]) { - let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); - crate::watch::new_submission(); - crate::descriptor::resync_title_writes(); - self.submit(&mut submitted, runs); - } - - fn submit(&self, submitted: &mut u64, runs: &[&HostList]) { + let was_working = working(true); + submitting(1, runs.len()); + // Flights in the air ([`late`]): a submission that is waited for + // settles them first, one sent ahead only if preparing it reads + // what they write. + if !late { + self.settle(&mut submitted, WHY_SYNC); + } else if let Some(why) = late_blocked(runs) { + if relay_exact() && why == WHY_READ { + // Only until the flights that may write what is read have + // landed: their copy-back's end, not the card's other work. + relay_wait(why, |line| blocked_by(&line.written, runs, false).is_none()); + } else { + self.settle(&mut submitted, why); + } + } + let behind = late && flying(); + // Before this submission counts as started: what the sweep lets go + // of is named by no list, and nothing runs now (behind flights the + // sweep waits for a submission that finds none in the air: there is + // one at every present). + static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if !behind { + sweep(); + SWEPT.store(now_ms(), Ordering::Relaxed); + } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 { + // With the present sent ahead nothing else brings a moment + // with nothing in the air: one is made for the sweep. + self.settle(&mut submitted, WHY_SYNC); + sweep(); + SWEPT.store(now_ms(), Ordering::Relaxed); + } + let behind = late && flying(); + // The slots that waited for a texture's host copy, before the + // lists that may read them run. + crate::descriptor::make_waiting(); + let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1; + // The ranges shaders write are counted for it (with the relay). + crate::shadow::preparing(this_submission); let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::Submissions, runs.len() as u64); - + let lock = (started - called).as_micros() as u64; + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Submissions, 1); + let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); + // Where each run's lists start in `lists`. + let mut firsts = Vec::with_capacity(runs.len()); let mut batch = Batch::default(); + // The time a settle of flights takes inside this preparing: the + // wait for the card and the copy-back have their own places on the + // frame line (run 92 showed them twice, "preparing" 250 ms for 135). + let mut settled = std::time::Duration::ZERO; + // One write-watch asking for everything the submission refreshes + // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges. + if crate::watch::once() { + let mut spans: std::collections::HashMap = std::collections::HashMap::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::Refresh(shadow, address, len) = step + && !shadow.unwatched() + { + let span = spans + .entry(std::sync::Arc::as_ptr(shadow) as usize) + .or_insert((*address, *address + *len)); + *span = (span.0.min(*address), span.1.max(*address + *len)); + } + } + } + let ranges: Vec<(usize, usize)> = spans.into_values().collect(); + crate::watch::ask_once(&ranges); + // Behind flights: the title wrote memory that a flight's shaders + // may write too, and this submission refreshes it. The flights + // are settled, and the asking made again: the copy-back wrote + // title memory, which other copies of it must see. + if behind && stale_under_flights(runs) { + let settling = std::time::Instant::now(); + self.settle(&mut submitted, WHY_STALE); + settled += settling.elapsed(); + crate::watch::ask_once(&ranges); + } + } else if behind && stale_under_flights(runs) { + let settling = std::time::Instant::now(); + self.settle(&mut submitted, WHY_STALE); + settled += settling.elapsed(); + } for list in runs { list.run_deferred(&mut batch); + firsts.push(lists.len()); + if let Some(prelude) = list.prelude() { + lists.push(Some(prelude)); + } + lists.push(list.list.cast().ok()); } batch.flush(); + crate::watch::ask_once_end(); + // The snapshots of the ranges shaders may write, if they were left + // for now (`crate::shadow::wide_back`): the refreshes are done, the + // lists have not gone to the card. + { + #[cfg(feature = "diagnostics")] + let snapshots = std::time::Instant::now(); + crate::shadow::take_snapshots(); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64); + } + // Copies in the card's memory: what changed on their CPU side goes + // up ahead of the lists, and a compare of what the shaders may + // write follows them in the same submission. + let flown = late && relay(); + if flown && self.card_results_low() { + let settling = std::time::Instant::now(); + self.settle(&mut submitted, WHY_MOST); + settled += settling.elapsed(); + } + let card = self.card_before(runs, flown); + if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) { + lists.push(Some(check)); + } let prepared = std::time::Instant::now(); - - // A run's prelude must be recorded immediately before that run is - // submitted. Preparing all preludes up front is incorrect when two - // runs use the same shadow: the later prelude would assume a state - // transition that the earlier command list has not executed yet. - #[allow(unused_variables)] - for (i, list) in runs.iter().enumerate() { - let mut group: Vec> = Vec::with_capacity(2); - if let Some(prelude) = list.prelude() { - group.push(Some(prelude)); - } - group.push(list.list.cast().ok()); - + if late { *submitted += 1; + // SAFETY: closed lists; the fence is ours. + let signalled = unsafe { + self.queue.ExecuteCommandLists(&lists); + self.queue.Signal(&self.fence, *submitted) + }; + self.card_sent(); + if let Err(e) = signalled { + fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); + } + let back = declared_writes(runs); + let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); + SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed); + submitting(0, 0); #[cfg(feature = "diagnostics")] - let list_started = std::time::Instant::now(); + crate::copystat::submission_ends(lock); + let sent = Sent { + number: this_submission, + card, + back, + writes, + }; + working(was_working); + return Some((submitted, sent)); + } + // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`). + #[cfg(feature = "diagnostics")] + let groups: Vec<&[Option]> = if timing() { + firsts + .iter() + .zip(firsts.iter().skip(1).chain([&lists.len()])) + .map(|(&a, &b)| &lists[a..b]) + .collect() + } else { + vec![&lists[..]] + }; + #[cfg(not(feature = "diagnostics"))] + let groups = [&lists[..]]; + submitting(2, runs.len()); + for (i, group) in groups.iter().enumerate() { + *submitted += 1; + let started = std::time::Instant::now(); // SAFETY: closed lists; the fence and event are ours. unsafe { - self.queue.ExecuteCommandLists(&group); + self.queue.ExecuteCommandLists(group); + self.card_sent(); let waited = self .queue .Signal(&self.fence, *submitted) .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); match waited { Ok(()) => { + working(false); WaitForSingleObject(self.event, INFINITE); - list.decay_shadows(); + stood(started); + working(true); } Err(e) => tracing::warn!(error = %e, "host submission not waited for"), } } + // With timing on each group is one of `runs` (and the compare + // of copies in the card's memory, with the last): every + // command's time on the card goes to the sums by pipeline. #[cfg(feature = "diagnostics")] - if runs.len() > 1 && list_started.elapsed() > std::time::Duration::from_millis(50) { + if timing() { // SAFETY: a plain query. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); - let commands = runs[i] - .notes - .lock() - .unwrap_or_else(|e| e.into_inner()) - .len(); - tracing::warn!( - ms = list_started.elapsed().as_millis(), - commands, - "slow host list" - ); + for (ms, op) in runs[i].slowest(frequency, usize::MAX) { + crate::copystat::command_took(&op, ms); + } + } + // A submission of one list was never named here (`groups.len() + // > 1` was the test): the two 50 ms lists of the gameplay + // frame, each a submission of its own, printed nothing. + #[cfg(feature = "diagnostics")] + if timing() && started.elapsed() > std::time::Duration::from_millis(50) { + // SAFETY: a plain query. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); + let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len(); + tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list"); for (ms, op) in runs[i].slowest(frequency, 6) { tracing::warn!("slow list command, {ms:.1} ms: {op}"); } } + let _ = (i, started); } + let _ = &firsts; + FINISHED.store(this_submission, Ordering::Release); + bury(this_submission); let gpu = prepared.elapsed(); SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed); SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::card_waited(gpu.as_micros() as u64, || { + let pipelines: std::collections::BTreeSet = runs + .iter() + .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone()) + .collect(); + let text = format!("{} lists, pipelines {pipelines:?}", runs.len()); + text.chars().take(1200).collect() + }); // The host resets a device whose submission runs for about 2 s. if gpu > std::time::Duration::from_millis(250) { let pipelines: std::collections::BTreeSet = runs .iter() - .flat_map(|l| { - l.pipelines - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clone() - }) + .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone()) .collect(); - tracing::warn!( - ms = gpu.as_millis(), - lists = runs.len(), - ?pipelines, - "slow host submission" - ); + tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission"); } // SAFETY: a plain query. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { @@ -765,36 +4211,56 @@ impl Host { last_notes(runs) )); } + submitting(3, runs.len()); // What shaders wrote goes back before the bottom-of-pipe writes, // which tell the title the GPU is done; each range once per // submission, however many dispatches declared it (the world's // passes declare the same big ranges dozens of times). let copying = std::time::Instant::now(); - // One list's lock at a time: a submission may name a list twice. - let mut back: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); - for list in runs { - for step in &list.deferred().copies { - if let Step::GpuWrite(shadow, address, len) = step - && !back.iter().any(|(s, a, l)| { - std::sync::Arc::ptr_eq(s, shadow) && (*a, *l) == (*address, *len) - }) - { - back.push((shadow.clone(), *address, *len)); - } - } + // For copies in the card's memory the compare has run there: the + // pieces that differ are fetched and merged. + if let Some(card) = &card { + self.card_back(card, &mut submitted, &mut std::collections::HashSet::new()); } - for (shadow, address, len) in &back { - let (address, len) = (*address, *len); - let written = shadow.copy_back(address, len); - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + let back = declared_writes(runs); + hand_back(&back); + if let Some(card) = card { + self.card_done(card); + } + #[cfg(feature = "diagnostics")] + if !back.is_empty() { + crate::copystat::add(crate::copystat::C::BackSubmissions, 1); + } + // Nothing of this submission goes back to the title: no range of + // shader writes, no value written when it is done. The wait for + // such a one is only for order and for what the card still holds. + #[cfg(feature = "diagnostics")] + if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) { + use crate::copystat::{C, add}; + add(C::NothingBack, 1); + add(C::NothingBackUs, gpu.as_micros() as u64); } COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed); for list in runs { + // Read backs first: a value written at the bottom of the pipe + // may be what tells the title that they are there. + read_backs(list); for &(at, what, bytes) in &list.deferred().writes { what.write(at as *mut u8, bytes); } } self.log_messages(); + submitting(0, 0); + #[cfg(feature = "diagnostics")] + crate::copystat::submission_ends(lock); + // With the relay: nothing is in the air now, so no fetch still to + // be merged is older than the sends to card copies so far, and + // their notes can go. + if relay() { + crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); + } + working(was_working); + None } /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations @@ -938,26 +4404,21 @@ impl Host { first_error } - /// A host render target view of `resource`, valid until it is recorded, - /// or `None` if the host resource lacks `ALLOW_RENDER_TARGET`. + /// A host render target view of `resource`, valid until it is recorded. pub(crate) fn rtv( &self, - resource: &ID3D12Resource, + resource: Option<&ID3D12Resource>, desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>, - ) -> Option { - // SAFETY: a live resource. - let flags = unsafe { resource.GetDesc() }.Flags; - if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 == 0 { - return None; - } + ) -> D3D12_CPU_DESCRIPTOR_HANDLE { let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING; - // SAFETY: a slot of our heap and a live resource. + // SAFETY: a slot of our heap and a live resource, or none with a + // description (a typed null view). unsafe { let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart(); handle.ptr += (slot * self.rtv_size) as usize; self.device .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle); - Some(handle) + handle } } @@ -991,20 +4452,14 @@ impl HostList { let device = &host()?.device; let mut heap: Option = None; let mut back: Option = None; - let readback = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_READBACK, - ..Default::default() - }; + let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: u64::from(STAMPS) * 8, Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; @@ -1012,11 +4467,7 @@ impl HostList { unsafe { device .CreateQueryHeap( - &D3D12_QUERY_HEAP_DESC { - Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, - Count: STAMPS, - NodeMask: 0, - }, + &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 }, &mut heap, ) .ok()?; @@ -1045,10 +4496,7 @@ impl HostList { return Vec::new(); }; let mut data = std::ptr::null_mut(); - let range = D3D12_RANGE { - Begin: 0, - End: (count + 1) * 8, - }; + let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 }; // SAFETY: a read-back buffer the finished list resolved into. let stamps: Vec = unsafe { if back.Map(0, Some(&range), Some(&mut data)).is_err() { @@ -1061,10 +4509,7 @@ impl HostList { let mut times: Vec<(f64, String)> = (0..count) .map(|i| { let ticks = stamps[i + 1].saturating_sub(stamps[i]); - ( - ticks as f64 * 1e3 / frequency.max(1) as f64, - notes[i].0.chars().take(300).collect(), - ) + (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect()) }) .collect(); times.sort_by(|a, b| b.0.total_cmp(&a.0)); @@ -1073,23 +4518,14 @@ impl HostList { } pub(crate) fn close(&self) { - if self.closed.swap(true, Ordering::AcqRel) { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!("a host command list closed twice; the second close does nothing") - }); - return; - } - self.flush_barriers(); + self.twins_to_depth(); #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { - let count = - (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); + let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); // SAFETY: an open list, our heap and read-back buffer. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count); - self.list - .ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0); + self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0); } } // SAFETY: our list. @@ -1103,29 +4539,23 @@ impl HostList { /// Only after the list's last submission finished (every one is waited /// for). pub(crate) fn reset(&self) { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + self._alive.used(); *self.deferred() = Deferred::default(); - self.states - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clear(); - self.shadow_states - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clear(); - self.pending_barriers - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clear(); - self.pipelines - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clear(); + self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); { let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); (scratch.current, scratch.used) = (0, 0); - scratch.copies.clear(); + // Every submission of the list has run: nothing reads its + // scratch memory any more, and the next list to ask takes it. + if scratch_pool() { + give_chunks(std::mem::take(&mut scratch.chunks)); + } } // SAFETY: the list is not executing. let reset = unsafe { @@ -1136,30 +4566,8 @@ impl HostList { if let Err(e) = reset { fail(format_args!("a host command list did not reset ({e})")); } - } - - /// Queues `barrier` until the next flush. Texture state users keep the - /// resource alive through the list's state map until the list is reset. - pub(crate) fn queue_barrier(&self, barrier: D3D12_RESOURCE_BARRIER) { - let mut pending = self - .pending_barriers - .lock() - .unwrap_or_else(|e| e.into_inner()); - push_barrier(&mut pending, barrier); - } - - /// Records queued texture transitions in one call before dependent work. - pub(crate) fn flush_barriers(&self) { - let mut pending = self - .pending_barriers - .lock() - .unwrap_or_else(|e| e.into_inner()); - if pending.is_empty() { - return; - } - // SAFETY: an open list; resources are alive through the list state map. - unsafe { self.list.ResourceBarrier(&pending) }; - pending.clear(); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64); } /// Moves a title texture's host copy to `wanted` (a host state) in this @@ -1187,164 +4595,288 @@ impl HostList { } } - /// Moves a shadow buffer to `wanted` in this list. Its real state is - /// tracked separately because D3D12 buffers decay to COMMON after each - /// ExecuteCommandLists operation. - pub(crate) fn transition_shadow( - &self, - shadow: &std::sync::Arc, - wanted: u32, - ) -> Option<(ID3D12Resource, u32)> { - let mut states = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); - match states.entry(std::sync::Arc::as_ptr(shadow) as usize) { + /// Moves host texture `copy` to `wanted` (a host state) in this list, + /// as [`HostList::transition`] does a title resource's host copy, and + /// records the barrier: for textures that are not a title resource's + /// host copy (colour twins) and for the copies between the two. + fn settle(&self, copy: &std::sync::Arc, wanted: u32) { + let wanted = legal_state(©.texture, wanted); + let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); + let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) { std::collections::hash_map::Entry::Vacant(v) => { - v.insert((wanted, wanted, shadow.clone())); + v.insert((wanted, wanted, copy.clone())); None } std::collections::hash_map::Entry::Occupied(mut o) => { let before = std::mem::replace(&mut o.get_mut().1, wanted); - if before != wanted { - tracing::debug!( - list = format_args!("{:#x}", self.list.as_raw() as usize), - resource = format_args!("{:#x}", shadow.buffer.as_raw() as usize), - before, - wanted, - "shadow state transition recorded" - ); - Some((shadow.buffer.clone(), before)) - } else { - None - } + (before != wanted).then_some(before) } + }; + drop(states); + if let Some(before) = before { + let barrier = transition( + ©.texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(wanted as i32), + ); + // SAFETY: an open list and a live texture. + unsafe { self.list.ResourceBarrier(&[barrier]) }; } } - /// Records a state change already emitted by a helper such as the - /// indirect-argument clamp, without adding another barrier. - pub(crate) fn note_shadow_state( + /// A use of title texture `resource` about to be recorded, if it is a + /// depth texture with a colour twin (false if it is not): of the twin + /// (`colour`: unordered access) or of the depth texture (depth target, + /// clear, shader read, copy, resolve), writing it or only reading. The + /// side used is first brought up to date: by a copy recorded here if + /// this list wrote the other side since, by the list's prelude if the + /// list uses the side as it finds it. The twin is left in the + /// unordered access state; the caller moves the depth texture to the + /// state its use needs, as for any texture. A twin still ahead when the + /// list closes is copied then (`twins_to_depth`). + /// shortcut: every depth target bound for a draw counts as written + /// (also when the draw only tests), and every unordered access view a + /// shader names as written; views a shader picks from the heap by a + /// computed index are not seen here at all. + pub(crate) fn twin_use( &self, - shadow: &std::sync::Arc, - state: u32, + resource: crate::object::This, + colour: bool, + write: bool, + ) -> bool { + const UNORDERED_ACCESS: u32 = 0x8; + // Asked for every texture a draw reads: most have no twin. + let Some(twin) = crate::resource::twin(resource) else { + return false; + }; + let Some(depth) = crate::resource::host_copy(resource) else { + return false; + }; + let side = usize::from(colour); + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + let u = twins + .entry(std::sync::Arc::as_ptr(&twin) as usize) + .or_insert_with(|| TwinUse { + depth: depth.clone(), + twin: twin.clone(), + needs: [false; 2], + behind: [None; 2], + writing: false, + late: false, + }); + let copy = match u.behind[side] { + Some(behind) => behind, + None => { + u.needs[side] = true; + false + } + }; + u.behind[side] = Some(false); + match (write, colour) { + // Shaders write the twin when the draw or dispatch runs: what + // the same one reads of the depth texture is prepared before + // (`twins_written`). + (true, true) => u.writing = true, + (true, false) => u.behind[1] = Some(true), + (false, _) => {} + } + // shortcut: the depth plane's twin is not drawn into the plane + // here: the pass sets a pipeline and a target of ours, which a list + // still recording the title's commands cannot take. This use sees + // the plane as it was; the pass runs when the list closes + // (`twins_to_depth`). Counted. + if copy && !colour && twin.plane.is_some() { + u.late = true; + crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed); + } + drop(twins); + if copy { + self.twin_copy(&depth, &twin, colour); + } else if colour { + self.settle(&twin.colour, UNORDERED_ACCESS); + } + // The depth plane's twin is written through unordered access too. + if colour && let Some(plane) = &twin.plane { + self.settle(plane, UNORDERED_ACCESS); + } + true + } + + /// Records the pass that draws the twin of the depth plane of `depth` + /// into the plane, if `twin` has one, with the moves to the states the + /// pass needs; the twin is left in the unordered access state. Only + /// for a list that records nothing of the title's afterwards + /// (`record_plane_pass`). + fn pass_plane( + &self, + depth: &std::sync::Arc, + twin: &crate::resource::Twin, ) { - let mut states = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); - let key = std::sync::Arc::as_ptr(shadow) as usize; - let previous = states.get(&key).map(|entry| entry.1); - states - .entry(key) - .and_modify(|entry| entry.1 = state) - .or_insert_with(|| (state, state, shadow.clone())); - tracing::debug!( - list = format_args!("{:#x}", self.list.as_raw() as usize), - resource = format_args!("{:#x}", shadow.buffer.as_raw() as usize), - previous, - state, - "shadow state set by helper" - ); + const UNORDERED_ACCESS: u32 = 0x8; + const DEPTH_WRITE: u32 = 0x10; + const PIXEL_SHADER_RESOURCE: u32 = 0x80; + let Some(plane) = &twin.plane else { return }; + self.settle(depth, DEPTH_WRITE); + self.settle(plane, PIXEL_SHADER_RESOURCE); + record_plane_pass(&self.list, &depth.texture, &plane.texture); + self.settle(plane, UNORDERED_ACCESS); } - /// Buffers decay to COMMON after a completed ExecuteCommandLists call. - fn decay_shadows(&self) { - let states = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); - for (_, last, shadow) in states.values() { - tracing::debug!( - list = format_args!("{:#x}", self.list.as_raw() as usize), - resource = format_args!("{:#x}", shadow.buffer.as_raw() as usize), - last, - "shadow state decayed to COMMON" - ); - shadow.state.store(0, Ordering::Relaxed); + /// Records the copy of a depth texture into its colour twin (`colour`) + /// or of the twin into the depth texture, with the moves to the copy + /// states. The twin is left in the unordered access state. + fn twin_copy( + &self, + depth: &std::sync::Arc, + twin: &crate::resource::Twin, + colour: bool, + ) { + const UNORDERED_ACCESS: u32 = 0x8; + const COPY_DEST: u32 = 0x400; + const COPY_SOURCE: u32 = 0x800; + let (from, to) = if colour { + (depth, &twin.colour) + } else { + (&twin.colour, depth) + }; + self.settle(from, COPY_SOURCE); + self.settle(to, COPY_DEST); + record_twin_copy(&self.list, &depth.texture, twin, colour); + self.settle(&twin.colour, UNORDERED_ACCESS); + } + + /// Before the list closes: the depth textures whose twins it wrote last + /// are given what was written, and left readable by shaders. Shaders + /// that pick a view from the heap by a computed index are not seen by + /// `twin_use` and read the depth texture in lists that never name it + /// (in a captured frame of the title no table names a shadow + /// map for reading but the pass that fills the next one). + fn twins_to_depth(&self) { + const SHADER_RESOURCE: u32 = 0x40 | 0x80; + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + let written: Vec<_> = twins + .values_mut() + .filter(|u| u.behind[0] == Some(true) || u.late) + .map(|u| { + // Not copied again if the list copied since the last write + // and only the depth plane's pass is left. + let copy = u.behind[0] == Some(true); + u.behind[0] = Some(false); + u.late = false; + (u.depth.clone(), u.twin.clone(), copy) + }) + .collect(); + drop(twins); + for (depth, twin, copy) in &written { + if *copy { + self.twin_copy(depth, twin, false); + } + // Nothing of the title's is recorded after this: the pass may + // leave its own pipeline and target set. + self.pass_plane(depth, twin); + self.settle(depth, SHADER_RESOURCE); + } + } + + /// The draw or dispatch just prepared is recorded: the twins it writes + /// now hold what their depth textures lack. + pub(crate) fn twins_written(&self) { + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + for u in twins.values_mut().filter(|u| u.writing) { + u.writing = false; + u.behind[0] = Some(true); } } /// At submission: the list that moves each texture this list uses from /// its real state to the one the list starts with; the textures' real - /// states become those the list ends with. + /// states become those the list ends with. For depth textures with a + /// colour twin it first copies the side the list uses as it finds it + /// from the other, if a list submitted earlier left it behind. fn prelude(&self) -> Option { - let uploads: Vec<_> = { - let deferred = self.deferred(); - deferred - .copies - .iter() - .filter_map(|step| match step { - Step::Texture(staging, copy) => Some((staging.clone(), copy.clone())), - _ => None, - }) - .collect() - }; - const COPY_DEST: u32 = D3D12_RESOURCE_STATE_COPY_DEST.0 as u32; + const COPY_DEST: u32 = 0x400; + const COPY_SOURCE: u32 = 0x800; + let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32); let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); - let mut barriers: Vec = Vec::new(); - let mut upload_copies = Vec::new(); - let mut after_uploads: Vec = Vec::new(); - for (first, last, copy) in states.values() { - let real = copy.state.swap(*last, Ordering::Relaxed); - let upload = uploads - .iter() - .find(|(_, host)| std::sync::Arc::ptr_eq(host, copy)) - .and_then(|(staging, _)| staging.take_upload().then_some(staging.clone())); - if let Some(staging) = upload { - if real != COPY_DEST { - barriers.push(transition( - ©.texture, - D3D12_RESOURCE_STATES(real as i32), - D3D12_RESOURCE_STATE_COPY_DEST, - )); - } - upload_copies.push((staging, copy.texture.clone())); - if COPY_DEST != *first { - after_uploads.push(transition( - ©.texture, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATES(*first as i32), - )); + // The copies (depth texture, twin, whether into the twin); the + // sides are then as this list leaves them. + let mut syncs = Vec::new(); + let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + for u in twins.values() { + let real = u.twin.behind.load(Ordering::Relaxed); + let mut behind = [real & 1 != 0, real & 2 != 0]; + for side in [0, 1] { + if u.needs[side] && behind[side] { + syncs.push((u.depth.clone(), u.twin.clone(), side == 1)); + behind = [false; 2]; } - } else if real != *first { - barriers.push(transition( - ©.texture, - D3D12_RESOURCE_STATES(real as i32), - D3D12_RESOURCE_STATES(*first as i32), - )); } + let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side])); + let left = u32::from(left[0]) | (u32::from(left[1]) << 1); + u.twin.behind.store(left, Ordering::Relaxed); } - drop(states); - let shadows = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); - barriers.extend(shadows.values().filter_map(|(first, last, shadow)| { - let real = shadow.state.swap(*last, Ordering::Relaxed); - if real != *first { - tracing::debug!( - list = format_args!("{:#x}", self.list.as_raw() as usize), - resource = format_args!("{:#x}", shadow.buffer.as_raw() as usize), - real, - first, - last, - "shadow submission prelude transition" - ); - Some(transition( - &shadow.buffer, - D3D12_RESOURCE_STATES(real as i32), - D3D12_RESOURCE_STATES(*first as i32), - )) + drop(twins); + // A copy runs with its textures in the copy states: each moves + // there from its real state, and from there to the state the list + // starts with (back to its real state if the list does not use it). + let mut to_copy = Vec::new(); + let mut barriers = Vec::new(); + let mut copying = std::collections::HashMap::new(); + for (depth, twin, colour) in &syncs { + let (from, to) = if *colour { + (depth, &twin.colour) } else { - None + (&twin.colour, depth) + }; + for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] { + let key = std::sync::Arc::as_ptr(texture) as usize; + let real = texture.state.load(Ordering::Relaxed); + copying.insert(key, state); + if real != state { + to_copy.push(transition( + &texture.texture, + host_state(real), + host_state(state), + )); + if !states.contains_key(&key) { + barriers.push(transition( + &texture.texture, + host_state(state), + host_state(real), + )); + } + } } + } + barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| { + let real = copy.state.swap(*last, Ordering::Relaxed); + let real = copying.get(key).copied().unwrap_or(real); + (real != *first) + .then(|| transition(©.texture, host_state(real), host_state(*first))) })); - if barriers.is_empty() && upload_copies.is_empty() { + if barriers.is_empty() && syncs.is_empty() { return None; } - let (allocator, list) = &self.prelude; + let Some((allocator, list)) = self + .prelude + .get_or_init(|| host().and_then(|h| h.make_prelude())) + .as_ref() + else { + fail(format_args!("no host list for a state prelude")); + }; // SAFETY: the prelude is not executing (every submission is waited // for); the textures are live. let recorded = unsafe { allocator.Reset().and_then(|()| { list.Reset(allocator, None)?; - if !barriers.is_empty() { - list.ResourceBarrier(&barriers); + if !to_copy.is_empty() { + list.ResourceBarrier(&to_copy); } - for (staging, texture) in &upload_copies { - staging.record_upload(list, texture); + for (depth, twin, colour) in &syncs { + record_twin_copy(list, &depth.texture, twin, *colour); } - if !after_uploads.is_empty() { - list.ResourceBarrier(&after_uploads); + if !barriers.is_empty() { + list.ResourceBarrier(&barriers); } list.Close() }) @@ -1373,27 +4905,52 @@ impl HostList { #[cfg(feature = "diagnostics")] fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) { - if dred_on() { + if !dred_on() { + crate::capture::op(std::ptr::from_ref(self) as usize, what); + return; + } + { + let started = std::time::Instant::now(); let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32; - if let Some((heap, _)) = self.stamps() - && at < STAMPS - 1 - { + if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 { // SAFETY: an open list and our query heap. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) }; } let what = what(); + crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone()); let text: Vec = what.encode_utf16().chain([0]).collect(); const UNICODE: u32 = 0; // SAFETY: an open list; the marker is copied when recorded. unsafe { - self.list - .SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32) + self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32) }; self.notes .lock() .unwrap_or_else(|e| e.into_inner()) .push((what, range)); + crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64); + } + } + + /// Whether nothing recorded since the list was opened does any work: + /// no draw or dispatch (the first keeps its pipeline), no copy, clear, + /// upload or resolve (they defer a step or move a texture's state), no + /// bottom-of-pipe write. State set on the list does not count. + pub(crate) fn untouched(&self) -> bool { + { + let deferred = self.deferred(); + if !(deferred.copies.is_empty() + && deferred.uploads.is_empty() + && deferred.kept.is_empty() + && deferred.textures.is_empty() + && deferred.writes.is_empty() + && deferred.backs.is_empty()) + { + return false; + } } + self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty() } /// Notes a pipeline the list binds. @@ -1411,6 +4968,19 @@ impl HostList { /// Copies `len` bytes from `src` to `dst` when the list is submitted. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) { let mut deferred = self.deferred(); + COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed); + // A copy that goes on where the one recorded just before it ended, + // source and destination both: with `join_copies` the two are one + // step. + if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut() + && continues((*d, *s, *n), (dst as usize, src as usize, len)) + { + COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed); + if join_copies() { + *n += len; + return; + } + } deferred .copies .push(Step::Copy(dst as usize, src as usize, len)); @@ -1456,6 +5026,14 @@ impl HostList { .push(Step::GpuWrite(shadow.clone(), address, len)); } + /// A read back: once the list has run, `rows` rows of `row` bytes go + /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`) + /// to title memory at `dst`, pitched `pitch`. The buffer lives until + /// the list is reset. + pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) { + self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch])); + } + /// Stores `what` (`bytes` of it) at `dst` once the list has run. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) { self.deferred().writes.push((dst as usize, what, bytes)); @@ -1468,76 +5046,50 @@ impl HostList { pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { let (buffer, data) = host.upload_buffer(size)?; name(&buffer, || format!("list upload {size:#x}")); - self.deferred().uploads.push(buffer.clone()); + self.deferred().hold_upload(buffer.clone(), size); 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)> { - let (_, at, gpu, data) = self.scratch_in(len.max(1).next_multiple_of(256), 256)?; - Some((gpu + at, data)) - } - - /// `len` bytes of upload memory aligned to `align` until the list is - /// reset: the host resource, byte offset within it, and CPU pointer. - pub(crate) fn scratch_aligned( - &self, - len: u64, - align: u64, - ) -> Option<(ID3D12Resource, u64, *mut u8)> { - let (buf, at, _, data) = self.scratch_in(len.max(1), align.max(1))?; - Some((buf, at, data)) - } - - /// An element-aligned copy of `len` title bytes at `src`, filled at - /// submission and shared by every use in this list until it is reset: - /// the host buffer and the copy's byte offset in it. - pub(crate) fn aligned_copy( - &self, - src: u64, - len: u64, - align: u64, - ) -> Option<(ID3D12Resource, u64)> { - let key = (src, len, align); - let scratch = || self.scratch.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(hit) = scratch().copies.get(&key) { - return Some(hit.clone()); - } - let (buf, at, to) = self.scratch_aligned(len, align)?; - self.defer_fill(to, src as *const u8, len as usize); - scratch().copies.insert(key, (buf.clone(), at)); - Some((buf, at)) - } - - fn scratch_in(&self, len: u64, align: u64) -> Option<(ID3D12Resource, u64, u64, *mut u8)> { let host = host()?; let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + let len = len.max(1).next_multiple_of(256); if len > SCRATCH_CHUNK { let (buffer, data) = host.upload_buffer(len)?; name(&buffer, || format!("list scratch {len:#x}")); // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - self.deferred().uploads.push(buffer.clone()); - return Some((buffer, 0, gpu, data)); + self.deferred().hold_upload(buffer, len); + return Some((gpu, data)); } - let at = s.used.next_multiple_of(align); - if at + len > SCRATCH_CHUNK && s.current < s.chunks.len() { + // The chunk in use while `len` fits in what is left of it, else the + // next one (a list's first chunk may be a small one). + while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 { (s.current, s.used) = (s.current + 1, 0); } if s.current == s.chunks.len() { - let (buffer, data) = host.upload_buffer(SCRATCH_CHUNK)?; - name(&buffer, || "list scratch".into()); - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - s.chunks.push((buffer, data as usize, gpu)); + let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST { + SCRATCH_FIRST + } else { + SCRATCH_CHUNK + }; + let chunk = take_chunk(host, size)?; + s.chunks.push((chunk, size)); s.used = 0; } - let buffer = s.chunks[s.current].0.clone(); - let (_, data, gpu) = s.chunks[s.current]; - let at = s.used.next_multiple_of(align); - s.used = at + len; - Some((buffer, at, gpu, (data + at as usize) as *mut u8)) + let (data, gpu) = (s.chunks[s.current].0.data, s.chunks[s.current].0.gpu); + let at = s.used; + s.used += len; + Some((gpu + at, (data + at as usize) as *mut u8)) + } + + /// The bytes of scratch chunks the list holds now (after a reset: + /// none while lists share their chunks). + pub(crate) fn scratch_kept(&self) -> u64 { + let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + scratch.chunks.iter().map(|c| c.1).sum() } /// The host address of the list's indirect-work budget, zeroed at each @@ -1554,15 +5106,51 @@ impl HostList { if !deferred.budget_zeroed { deferred.budget_zeroed = true; let at = *data; - // SAFETY: the list's own mapped word, written before it runs. + // SAFETY: the list's own mapped words, written before it runs. + // The words after the budget hold what the clamp noted about the + // list's last run (mesh dispatches: the largest group count + // asked for, the groups asked in all): taken, then zeroed. deferred.copies.push(Step::Host(Box::new(move || unsafe { - (at as *mut u32).write_volatile(0) + let words = at as *mut u32; + let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile()); + MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed); + MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed); + for k in 0..3 { + words.add(k).write_volatile(0); + } }))); } // SAFETY: a live buffer. Some(unsafe { buffer.GetGPUVirtualAddress() }) } + /// A device-local unordered-access buffer of at least `size` bytes for + /// clamped indirect arguments, reused across executions and resets of the + /// list. Smaller buffers replaced mid-list stay alive until + /// [`HostList::reset`]. + pub(crate) fn indirect_scratch(&self, size: u64) -> Option { + let needed = size.max(64 << 10); + let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((buffer, cap)) = &*slot + && *cap >= needed + { + return Some(buffer.clone()); + } + let prev = slot.as_ref().map_or(0, |(_, cap)| *cap); + let alloc = prev + .saturating_mul(2) + .max(needed) + .next_multiple_of(64 << 10); + let buffer = host()?.uav_buffer(alloc)?; + name(&buffer, || format!("indirect arguments {alloc:#x}")); + let old = slot.replace((buffer.clone(), alloc)); + drop(slot); + if let Some((old_buf, _)) = old { + self.keep(&old_buf); + } + Some(buffer) + } + /// Keeps `object` alive until the list is reset. pub(crate) fn keep(&self, object: &impl Interface) { if let Ok(object) = object.cast::() { @@ -1590,12 +5178,8 @@ impl HostList { /// 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, - copy: std::sync::Arc, - ) { - self.deferred().copies.push(Step::Texture(staging, copy)); + pub(crate) fn defer_texture(&self, staging: std::sync::Arc) { + self.deferred().copies.push(Step::Texture(staging)); } /// Runs the list's submission-time steps; refreshes go into `batch` @@ -1605,7 +5189,7 @@ impl HostList { #[cfg(feature = "diagnostics")] use crate::copystat::{C, add}; for step in &self.deferred().copies { - let mut started = std::time::Instant::now(); + let started = std::time::Instant::now(); let copied = match step { &Step::Copy(dst, src, len) => { #[cfg(feature = "diagnostics")] @@ -1614,9 +5198,9 @@ impl HostList { add(C::CopyBytes, len as u64); } batch.title_written(); - // The flush counted its own time; the copy starts here. - started = std::time::Instant::now(); copy_mapped(dst as *mut u8, src as *const u8, len, true); + // With the submission's one asking: the journal learns it. + crate::watch::wrote(dst, len); len } &Step::Fill(dst, src, len) => { @@ -1640,12 +5224,13 @@ impl HostList { Step::Run(work) | Step::Host(work) => { if matches!(step, Step::Run(_)) { batch.title_written(); - #[cfg(feature = "diagnostics")] - { - started = std::time::Instant::now(); - } } work(); + // It wrote title memory, where is not known here: the + // submission's one asking ends, later refreshes ask anew. + if matches!(step, Step::Run(_)) { + crate::watch::ask_once_end(); + } #[cfg(feature = "diagnostics")] { add(C::Runs, 1); @@ -1654,12 +5239,23 @@ impl HostList { continue; } Step::GpuWrite(shadow, address, len) => { - // The shaders start from the title's data. - batch.flush(); + // The shaders start from the title's data: this copy's + // pending refresh first. The other copies' wait for + // the next flush of all (flushing all of them at every + // range a dispatch writes made thousands of write-watch + // askings a frame). + batch.flush_one(shadow); + #[cfg(feature = "diagnostics")] + let snapshot = std::time::Instant::now(); shadow.writing(*address, *len); + #[cfg(feature = "diagnostics")] + { + add(C::GpuWrites, 1); + add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64); + } continue; } - Step::Texture(staging, _) => { + Step::Texture(staging) => { if batch.texture_due(staging) { staging.refresh(); } @@ -1672,6 +5268,23 @@ impl HostList { } } +/// Whether a submission's refreshes of host copies run on several threads, +/// a copy to a thread (`VICTORY_WIDE_REFRESH=1`; off by default). +/// +/// A submission brings some sixty copies up to date, one after the other +/// on the submitting thread: for each, the pages the title wrote are asked +/// for and read through the kernel into the copy. That is the frame line's +/// "copies", 45-50 ms a frame, and the copies have nothing to do with one +/// another: each refresh writes its own copy and its own notes, and reads +/// title memory. With the switch the copies of a flush (four or more) are +/// spread over the threads kept for the snapshots (`crate::shadow::wide`). +/// The write-watch journal and the guards are behind their own locks, as +/// they are for the title's threads. +fn wide_refresh() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_REFRESH").is_some_and(|v| v == "1")) +} + /// A submission's refreshes not done yet, merged per buffer copy into the /// range that covers them: done before a step that writes title memory or /// gives a range to shaders, and before the lists run. @@ -1683,6 +5296,11 @@ impl HostList { #[derive(Default)] struct Batch { refreshes: Vec<(std::sync::Arc, usize, usize)>, + /// Where each copy (by address) is in `refreshes`: the list that makes + /// the heap's buffers ready adds some 4,100 copies, and searching them + /// for every refresh of a submission was tens of millions of + /// comparisons a frame. + index: std::collections::HashMap, /// Staging buffers (by address) refreshed since the last title write. textures: std::collections::HashSet, } @@ -1690,21 +5308,48 @@ struct Batch { impl Batch { fn add(&mut self, shadow: &std::sync::Arc, address: usize, len: usize) { let end = address + len; - match self - .refreshes - .iter_mut() - .find(|(s, ..)| std::sync::Arc::ptr_eq(s, shadow)) - { - Some((_, from, to)) => (*from, *to) = ((*from).min(address), (*to).max(end)), - None => self.refreshes.push((shadow.clone(), address, end)), + let key = std::sync::Arc::as_ptr(shadow) as usize; + match self.index.get(&key) { + Some(&at) => { + let r = &mut self.refreshes[at]; + (r.1, r.2) = (r.1.min(address), r.2.max(end)); + } + None => { + self.index.insert(key, self.refreshes.len()); + self.refreshes.push((shadow.clone(), address, end)); + } + } + } + + /// Before shaders are given a range of `shadow`'s copy: its pending + /// refresh is done, the others stay pending. + fn flush_one(&mut self, shadow: &std::sync::Arc) { + let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else { + return; + }; + let (shadow, from, to) = self.refreshes.swap_remove(at); + // The last entry took its place. + if let Some(moved) = self.refreshes.get(at) { + self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at); } + Self::update(&shadow, from, to); + } + + /// Brings `[from, to)` of a copy up to date, timed. + fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) { + let started = std::time::Instant::now(); + let copied = shadow.update(from, to - from); + let us = started.elapsed().as_micros() as u64; + #[cfg(feature = "diagnostics")] + crate::copystat::range(from, to - from, us, 0); + PREPARING[0].fetch_add(us, Ordering::Relaxed); + PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); } /// 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) + self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize) } /// Before a step that writes title memory: pending refreshes are done @@ -1715,22 +5360,43 @@ impl Batch { } fn flush(&mut self) { - let started_flush = std::time::Instant::now(); - let ((), pieces) = crate::copy_pool::queued(|| { + self.index.clear(); + // One write-watch asking for the copies that lie close together, + // not one per copy. + let ahead = self.refreshes.len() > 1; + if ahead { + let started = std::time::Instant::now(); + let ranges: Vec<(usize, usize)> = self + .refreshes + .iter() + .filter(|r| !r.0.unwatched()) + .map(|r| (r.1, r.2)) + .collect(); + crate::watch::ask_ahead(&ranges); + PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + } + if wide_refresh() && self.refreshes.len() >= 4 { + // Each copy on its own, several at a time: a copy's refresh + // writes that copy and reads title memory, nothing of another's. + // The time counted is the time it took, not the threads' sum. + let started = std::time::Instant::now(); + let before = PREPARING[0].load(Ordering::Relaxed); + let jobs: Vec> = self + .refreshes + .drain(..) + .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box) + .collect(); + crate::shadow::wide_run(jobs); + let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before); + PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed); + } else { for (shadow, from, to) in self.refreshes.drain(..) { - #[cfg(feature = "diagnostics")] - let started = std::time::Instant::now(); - let copied = shadow.update(from, to - from); - #[cfg(feature = "diagnostics")] - crate::copystat::range(from, to - from, started.elapsed().as_micros() as u64, 0); - PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + Self::update(&shadow, from, to); } - }); - crate::copy_pool::run(pieces); - PREPARING[0].fetch_add( - started_flush.elapsed().as_micros() as u64, - Ordering::Relaxed, - ); + } + if ahead { + crate::watch::ask_ahead_done(); + } } } @@ -1757,6 +5423,19 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b if len == 0 { return; } + // A title destination that is not all mapped is left alone. Asking + // Windows first (`VirtualQuery`) walks the page tables to the end of + // the destination's region: in the title's big blocks that is + // milliseconds a copy, and it was a seventh of the submitting thread's + // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below + // says the same when it fails, so the question is only asked then. + // `VICTORY_COPY_ASK=1` asks first, as before. + static ASK: OnceLock = OnceLock::new(); + let ask_first = title_dst + && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1")); + if ask_first && !crate::texture::committed(dst, len) { + return; + } if title_dst { // The kernel writes the destination: it must not be guarded. crate::watch::writing(dst as usize, len); @@ -1765,22 +5444,63 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b let moved = std::time::Instant::now(); let whole = read(src, dst, len); #[cfg(feature = "diagnostics")] - crate::copystat::add( - crate::copystat::C::MoveUs, - moved.elapsed().as_micros() as u64, - ); + crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64); if whole { return; } - // The kernel reports an unmapped destination as it does a source, so - // `VirtualQuery` (which walks page tables to the region's end, ~1 ms a - // copy in the title's pools, ~100 ms per world frame) is asked only - // after a failure: a destination not all mapped is left alone. - if title_dst && !crate::texture::committed(dst, len) { + // The copy failed: a source page is not there, or the destination is + // not all mapped. Then the destination stays as it is (the kernel may + // have written its first pages). + if title_dst && !ask_first && !crate::texture::committed(dst, len) { return; } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Fallbacks, 1); + #[cfg(feature = "diagnostics")] + let sparse = std::time::Instant::now(); + if !title_dst && len >= 64 << 10 { + read_sparse(src, dst, len); + } else { + read_pieces(src, dst, len); + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64); +} + +/// After a failed bulk read into host memory, skip contiguous holes. Never +/// cache the query across copies: the title may remap the same address. +fn read_sparse(src: *const u8, dst: *mut u8, len: usize) { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery, + }; + let mut offset = 0; + while offset < len { + let at = src.wrapping_add(offset); + let to = dst.wrapping_add(offset); + let remaining = len - offset; + // SAFETY: the query inspects an address and fills a local structure. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) }; + let n = (info.BaseAddress as usize).saturating_add(info.RegionSize) + .saturating_sub(at as usize).min(remaining); + if size != size_of_val(&info) || n == 0 { + read_pieces(at, to, remaining); + break; + } + if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Unmapped, n as u64); + // SAFETY: this path is only used with a writable host destination. + unsafe { to.write_bytes(0, n) }; + } else if !read(at, to, n) { + // A mapping may change between query and read. + read_pieces(at, to, n); + } + offset += n; + } +} + +fn read_pieces(src: *const u8, dst: *mut u8, len: usize) { // 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| { @@ -1816,64 +5536,51 @@ fn read(src: *const u8, dst: *mut u8, len: usize) -> bool { unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 } } -/// `NtWriteVirtualMemory`, looked up once. `WriteProcessMemory` asks the -/// kernel about the destination's region first (to flush the instruction -/// cache of executable memory), which in the title's big pools walks page -/// tables for about 2 ms a call: the copy back after a world submission -/// spent over a second there. The system call itself writes the same bytes -/// and reports a page it cannot write the same way. -fn nt_write_virtual_memory() -> Option { - use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; - static CALL: std::sync::OnceLock> = std::sync::OnceLock::new(); - *CALL.get_or_init(|| { - // SAFETY: ntdll is always loaded; the symbol has this signature. - unsafe { - let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); - let f = GetProcAddress(ntdll, c"NtWriteVirtualMemory".as_ptr().cast())?; - Some(std::mem::transmute::< - unsafe extern "system" fn() -> isize, - NtWrite, - >(f)) - } - }) +#[link(name = "ntdll", kind = "raw-dylib")] +unsafe extern "system" { + /// The kernel's write into a process's memory, `(process, address, + /// bytes, length, written out)`: an NTSTATUS, negative when a page of + /// the range is not there or not writable. It changes no protection. + fn NtWriteVirtualMemory( + process: *mut std::ffi::c_void, + base: *mut std::ffi::c_void, + buffer: *const std::ffi::c_void, + size: usize, + written: *mut usize, + ) -> i32; } -type NtWrite = unsafe extern "system" fn( - process: isize, - base: *mut core::ffi::c_void, - buffer: *const core::ffi::c_void, - len: usize, - written: *mut usize, -) -> i32; +/// Whether title memory is written with the kernel's own call +/// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks +/// what the pages are (as `VirtualQuery` does: about 2 ms a call in the +/// title's big pools, see [`copy_mapped`]): putting back what shaders wrote +/// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size +/// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before. +fn direct_writes() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0")) +} /// Copies host memory into title memory after a submission (what shaders /// wrote), leaving pages that are not mapped alone. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; - let nt = nt_write_virtual_memory(); + let direct = direct_writes(); let write = |at: usize, n: usize| { let from = src.wrapping_add(at - dst as usize); let mut done = 0; + if direct { + // SAFETY: as below; the kernel checks the destination and + // writes nothing it cannot (the caller opened its guards: + // `crate::watch::writing`). + return unsafe { + NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0 + }; + } // SAFETY: the source is our mapped host copy; the kernel checks the // destination. - unsafe { - match nt { - // STATUS_SUCCESS only: a partial copy is a failure here too. - Some(call) => { - call( - GetCurrentProcess() as isize, - at as _, - from.cast(), - n, - &mut done, - ) == 0 - } - None => { - WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 - } - } - } + unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 } }; if len == 0 || write(dst as usize, len) { return; @@ -1881,12 +5588,7 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { for_pieces(dst as usize, len, 64 << 10, |at, n| { if !write(at, n) { for_pieces(at, n, 4 << 10, |at, n| { - // Wine does not write into write-watched pages not written - // since they were committed (ERROR_PARTIAL_COPY), but reads - // into them. The kernel checks this destination as well. - if !write(at, n) { - read(src.wrapping_add(at - dst as usize), at as *mut u8, n); - } + write(at, n); }); } }); @@ -1905,15 +5607,12 @@ fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, us } impl Host { - /// A default-heap GPU buffer, starting in `UNORDERED_ACCESS` when its - /// flags allow unordered access. - pub(crate) fn default_buffer( - &self, - size: u64, - flags: D3D12_RESOURCE_FLAGS, - ) -> Option { + /// A buffer in the upload heap, mapped for writing. + /// A buffer of `size` bytes the card writes and we read (a read back), + /// in the state copies into it need. + pub(crate) fn read_back_buffer(&self, size: u64) -> Option { let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, + Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { @@ -1927,22 +5626,16 @@ impl Host { Quality: 0, }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: flags, ..Default::default() }; - let state = if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0 { - D3D12_RESOURCE_STATE_UNORDERED_ACCESS - } else { - D3D12_RESOURCE_STATE_COMMON - }; let mut buffer: Option = None; - // SAFETY: plain default-heap buffer allocation with valid descriptions. + // SAFETY: plain creation of a read-back buffer. let made = unsafe { self.device.CreateCommittedResource( &heap, D3D12_HEAP_FLAG_NONE, &desc, - state, + D3D12_RESOURCE_STATE_COPY_DEST, None, &mut buffer, ) @@ -1950,16 +5643,15 @@ impl Host { match made { Ok(()) => buffer, Err(e) => { - tracing::warn!(error = %e, size, "no default buffer"); + tracing::warn!(error = %e, size, "no read-back buffer"); None } } } -} -impl Host { - /// A buffer in the upload heap, mapped for writing. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + MADE[0].fetch_add(1, Ordering::Relaxed); + MADE[1].fetch_add(size, Ordering::Relaxed); let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() @@ -2025,6 +5717,10 @@ struct Presenter { height: u32, format: DXGI_FORMAT, copy: HostList, + /// With presents sent ahead ([`late_free_present`]): a list for each + /// present in the air, and the submission it last flew as (it is used + /// again once that one has finished). + ahead: Vec<(HostList, u64)>, hwnd: HWND, meter: Meter, } @@ -2044,8 +5740,6 @@ struct Meter { impl Meter { fn new() -> Self { - #[cfg(feature = "diagnostics")] - crate::profile::start(); let now = std::time::Instant::now(); Meter { since: now, @@ -2062,6 +5756,8 @@ impl Meter { fn frame(&mut self, hwnd: HWND) { #[cfg(feature = "diagnostics")] tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present"); + #[cfg(feature = "diagnostics")] + crate::copystat::presented(); self.frames += 1; #[cfg(feature = "diagnostics")] { @@ -2078,28 +5774,161 @@ impl Meter { let draws = (drawn - self.drawn) as f64 / frames; (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn); // Of a frame, ms preparing submissions and ms waiting for the GPU. - let [cpu, gpu] = - [0, 1].map(|i| SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + let [cpu, gpu] = [0, 1].map(|i| { + SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames + }); let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| { let scale = if i % 2 == 0 { 1e3 } else { 1e6 }; PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames }); - let [back_ms, back_mb] = - [0, 1].map(|i| COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames); + let [back_ms, back_mb] = [0, 1].map(|i| { + COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames + }); let dropped = crate::draw::take_dropped() as f64 / frames; let indirect = crate::list::take_indirect() as f64 / frames; + let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed); + let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames; + tracing::info!( + "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame" + ); + late_line(frames); + card_clock_line(frames, ms); + crate::shadow::back_line(frames); + { + let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); + if passes + compares > 0.0 { + tracing::info!( + "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \ + ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes", + if rehash_runs() { "on" } else { "off" } + ); + } + } + { + let [own, asking, still, all] = + [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + if all >= 1.0 { + tracing::info!( + "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \ + is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \ + hold still (the runtime remapping it); the rest is reading, hashing and detiling" + ); + } + let [through, left] = [0, 1].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); + if through + left > 0.0 { + tracing::info!( + "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \ + {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there)" + ); + } + } + { + let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames); + if copies > 0.0 { + tracing::info!( + "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \ + (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})", + if join_copies() { "on" } else { "off" } + ); + } + } + // Passes over the heap's buffer views for shaders that pick them by index. + let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames; + let picked_ms = + crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames; + // Copies between depth textures and their colour twins, each way. + let [twin_to_depth, twin_to_colour] = + [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames); + // Depth planes drawn from their twins. + let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames; + // Copies in the card's memory (`crate::shadow::cards`). + let card = crate::shadow::card_stats(); + #[cfg(feature = "diagnostics")] + let slow = crate::watch::slow_asks(); // Over the same frames as the counts above. #[cfg(feature = "diagnostics")] let drops = crate::pipeline::take_drops(); if self.logged.elapsed() >= std::time::Duration::from_secs(5) { self.logged = std::time::Instant::now(); + tracing::info!( + "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)", + crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed) + ); + { + let [queued, due, away, partly, oldest] = + [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); + let [same, parts, tails] = + [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed)); + tracing::info!( + "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \ + {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \ + the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \ + as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \ + {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \ + {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \ + {} made slots found unmapped and made null", + crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed), + crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed), + crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed), + crate::descriptor::host::STALE[0].load(Ordering::Relaxed), + crate::descriptor::host::STALE[1].load(Ordering::Relaxed), + crate::descriptor::host::STALE[2].load(Ordering::Relaxed), + crate::descriptor::host::STALE[3].load(Ordering::Relaxed), + crate::descriptor::host::STALE[4].load(Ordering::Relaxed) + ); + } + #[cfg(feature = "diagnostics")] + tracing::info!( + "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms", + slow[0] as f64 / frames, + slow[1] as f64 / 1e3 / frames, + slow[2] as f64 / 1e3 + ); + if crate::shadow::cards() { + let per_frame = |i: usize| card[i] as f64 / frames; + tracing::info!( + "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \ + {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \ + ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)", + card[7], + card[8] >> 20, + card[9] >> 20, + per_frame(0) / 1e6, + per_frame(1), + per_frame(2), + per_frame(3), + per_frame(4) / 1e6, + per_frame(5), + per_frame(6) / 1e3 + ); + } tracing::info!( "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \ GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \ dropped {dropped:.0} without a host pipeline ({making} being made) and \ - {indirect:.0} indirect", - making = crate::pipeline::making() + {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \ + textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \ + {picked_waiting} waiting, {picked_away} passed over unmapped; depth textures with unordered access: {du0} made, bound as depth {du1}x, cleared as depth {du2}x, unordered views refused {du3}x; buffer views left null as the host would refuse them: {refused}", + picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed), + picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20, + picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed), + picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed), + du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed), + du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed), + du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed), + du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed), + refused = format!( + "{}; depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass", + crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed), + crate::resource::TWINS[0].load(Ordering::Relaxed), + crate::resource::TWINS[1].load(Ordering::Relaxed), + crate::resource::PLANES[1].load(Ordering::Relaxed), + crate::resource::PLANES[2].load(Ordering::Relaxed) + ), + making = crate::pipeline::making(), + placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed), + objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed) ); #[cfg(feature = "diagnostics")] { @@ -2154,14 +5983,6 @@ impl Host { /// as frame `frame` (saved if captures are on). `None` if nothing was /// shown; else, in diagnostics builds, whether the frame was black. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option { - // Diagnostics: an intermediate target instead (VICTORY_SHOW_TARGET). - #[cfg(feature = "diagnostics")] - let shown = crate::capture::take_shown(); - #[cfg(feature = "diagnostics")] - let (texture, state) = match &shown { - Some((copy, s)) => (©.texture, *s), - None => (texture, state), - }; // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; let Some(format) = swap_format(desc.Format) else { @@ -2181,13 +6002,25 @@ impl Host { } let p = presenter.as_mut()?; if (p.width, p.height, p.format) != (width, height, format) { + // Presents sent ahead hold back buffers until they have run. + settle_now(WHY_SYNC); // SAFETY: no back buffer is held; every submission was waited for. let resized = unsafe { p.swap_chain .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0)) }; match resized { - Ok(()) => (p.width, p.height, p.format) = (width, height, format), + Ok(()) => { + (p.width, p.height, p.format) = (width, height, format); + tracing::info!( + width, + height, + format = format.0, + frame, + "the swap chain's buffers were made again for another size or format" + ); + self.log_video_memory("right after the swap chain's buffers were made again"); + } Err(e) => { tracing::warn!(error = %e, width, height, "swap chain not resized"); return None; @@ -2201,8 +6034,30 @@ impl Host { let Ok(back) = p.swap_chain.GetBuffer::(index) else { return None; }; - p.copy.reset(); - let list = &p.copy.list; + // Sent ahead ([`late_free_present`]) unless the frame is to be + // read back at once (a saved or listed frame): then a list of + // its own, one whose last flight has finished or a new one. + #[cfg(feature = "diagnostics")] + let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame); + #[cfg(not(feature = "diagnostics"))] + let read_now = false; + let slot = if late_free_present() && !read_now { + let finished = FINISHED.load(Ordering::Acquire); + p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| { + let list = self.new_list().ok()?; + list.close(); + p.ahead.push((list, 0)); + Some(p.ahead.len() - 1) + }) + } else { + None + }; + let copy = match slot { + Some(i) => &p.ahead[i].0, + None => &p.copy, + }; + copy.reset(); + let list = ©.list; list.ResourceBarrier(&[ transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), transition( @@ -2217,7 +6072,7 @@ impl Host { .then(|| crate::capture::read_back(&self.device, list, texture)) .flatten(); #[cfg(feature = "diagnostics")] - let probe = crate::capture::probe(&self.device, list, texture); + let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) }; #[cfg(not(feature = "diagnostics"))] let _ = frame; list.ResourceBarrier(&[ @@ -2228,8 +6083,14 @@ impl Host { D3D12_RESOURCE_STATE_PRESENT, ), ]); - p.copy.close(); - self.execute(&[&p.copy]); + copy.close(); + match slot { + Some(i) => { + let flown = self.execute_own(copy); + p.ahead[i].1 = flown; + } + None => self.execute(&[copy]), + } #[cfg(feature = "diagnostics")] if let Some((buffer, footprint)) = capture { crate::capture::save_read_back(frame, &buffer, &footprint); @@ -2253,6 +6114,7 @@ impl Host { Some(hwnd) => hwnd, None => window(width, height)?, }; + self.log_video_memory("right before the swap chain is made"); // SAFETY: plain object creation for our window. unsafe { let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; @@ -2275,12 +6137,14 @@ impl Host { let copy = self.new_list()?; copy.close(); tracing::info!(width, height, format = format.0, "presenting to a window"); + self.log_video_memory("right after the swap chain is made"); Ok(Presenter { swap_chain, width, height, format, copy, + ahead: Vec::new(), hwnd, meter: Meter::new(), }) @@ -2336,11 +6200,95 @@ pub(crate) fn legal_for(flags: u32, state: u32) -> u32 { } impl Host { + /// The card's memory as the system accounts it to this process, in + /// bytes: the budget and the use of the card's own memory, then of the + /// PC's memory shared with the card (where the system moves what does + /// not fit on the card). + pub(crate) fn video_memory(&self) -> Option<[u64; 4]> { + let adapter = self.adapter.as_ref()?; + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries that fill our structures. + unsafe { + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) + .ok()?; + } + // The card's budget moved by 256 MB or more since the last look: + // said at once, with what was in use at the last look, so the log + // has the moment. (It fell from 11,242 MB to some 10,300 MB with + // the first world frame in runs 179 to 185, and the memory line, + // seconds later, was the first to show it. We reserve nothing + // and make the swap chain once, at the start.) + static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage]; + let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed)); + if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) { + tracing::info!( + "the system changed the budget of the card's memory from {} MB to {} MB (frame {}); at the last look {} MB of the card's and {} MB of the PC's shared memory were in use", + last[0] >> 20, + own.Budget >> 20, + crate::frame::current(), + last[1] >> 20, + last[2] >> 20 + ); + self.log_video_memory("right after that change"); + } + Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage]) + } + + /// Both of the system's memory groups for this process, in bytes: for + /// the card's own memory and then for the PC's memory shared with the + /// card, the budget, the use, what could still be reserved and what + /// is reserved (the layer reserves none). + pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> { + let adapter = self.adapter.as_ref()?; + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries that fill our structures. + unsafe { + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) + .ok()?; + } + let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| { + [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation] + }; + Some([all(&own), all(&shared)]) + } + + /// Logs [`Self::video_memory_groups`], with `when` it is said. + pub(crate) fn log_video_memory(&self, when: &str) { + let Some([own, shared]) = self.video_memory_groups() else { + return; + }; + tracing::info!( + "video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved; the PC's shared with the card: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved (the layer reserves none)", + when, + own[0] >> 20, + own[1] >> 20, + own[2] >> 20, + own[3] >> 20, + shared[0] >> 20, + shared[1] >> 20, + shared[2] >> 20, + shared[3] >> 20 + ); + } + /// 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 /// the common state (buffers move out of it implicitly). pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + MADE[2].fetch_add(1, Ordering::Relaxed); + MADE[3].fetch_add(size, Ordering::Relaxed); let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, @@ -2387,6 +6335,50 @@ impl Host { } } } + + /// A device-local buffer shaders may write (unordered access) and indirect + /// execution may read, starting in the common state. + pub(crate) fn uav_buffer(&self, size: u64) -> Option { + MADE[4].fetch_add(1, Ordering::Relaxed); + MADE[5].fetch_add(size, Ordering::Relaxed); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain creation of a device-local buffer. + let made = unsafe { + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + }; + match made { + Ok(()) => buffer, + Err(e) => { + tracing::warn!(error = %e, size, "no unordered-access buffer"); + None + } + } + } } /// For adapters without device-removed data (the software one): the last @@ -2399,11 +6391,7 @@ fn last_notes(runs: &[&HostList]) -> String { for (i, r) in runs.iter().enumerate() { let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); for (n, _) in notes.iter().rev().take(6).rev() { - text.push_str(&format!( - "; list {i} of {}, of its {}: {n}", - runs.len(), - notes.len() - )); + text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len())); } } text @@ -2434,23 +6422,19 @@ fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String { /// barriers overlaps on the GPU), by kind, and what the markers just /// before them say (`HostList::note_op`: diagnostics builds with /// device-removed data on). -fn in_flight( - history: &[D3D12_AUTO_BREADCRUMB_OP], - markers: &[(u32, String)], - done: usize, -) -> String { +fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String { let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER; - let from = history[..done] - .iter() - .rposition(barrier) - .map_or(0, |b| b + 1); + let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1); let to = history[done..] .iter() .position(barrier) .map_or(history.len(), |b| (done + b).max(done + 1)); let mut text = format!(", commands {from}..{to} between its barriers:"); let mut shown = 0; - for i in from..to { + // From just before the command the GPU had not finished: the first + // twelve after the barrier named draws long done when a list of 79 + // mesh draws stopped at its 45th (run 41). + for i in from.max(done.saturating_sub(4))..to { let op = history[i]; if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 { continue; @@ -2466,62 +6450,6 @@ fn in_flight( text } -/// Appends `barrier`, folding a transition into the queued transition of -/// the same resource it continues. Split barriers are never folded. -fn push_barrier(barriers: &mut Vec, barrier: D3D12_RESOURCE_BARRIER) { - if barrier.Type != D3D12_RESOURCE_BARRIER_TYPE_TRANSITION - || barrier.Flags != D3D12_RESOURCE_BARRIER_FLAG_NONE - { - barriers.push(barrier); - return; - } - // SAFETY: a transition barrier. - let next = unsafe { &barrier.Anonymous.Transition }; - if next.StateBefore == next.StateAfter { - return; - } - let raw = next.pResource.as_ref().map(Interface::as_raw); - for i in (0..barriers.len()).rev() { - if barriers[i].Type != D3D12_RESOURCE_BARRIER_TYPE_TRANSITION { - break; - } - let flags = barriers[i].Flags; - // SAFETY: a transition barrier. - let prev = unsafe { &mut barriers[i].Anonymous.Transition }; - if prev.pResource.as_ref().map(Interface::as_raw) != raw { - continue; - } - if flags == D3D12_RESOURCE_BARRIER_FLAG_NONE - && prev.Subresource == next.Subresource - && prev.StateAfter == next.StateBefore - { - if prev.StateBefore == next.StateAfter { - if next.StateAfter.0 & D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 != 0 { - // A round trip out of unordered access still orders the - // writes before and after it. - barriers[i] = D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, - Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, - Anonymous: D3D12_RESOURCE_BARRIER_0 { - UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { - // SAFETY: a borrowed pointer; the barrier never releases it. - pResource: unsafe { std::mem::transmute_copy(&prev.pResource) }, - }), - }, - }; - } else { - barriers.remove(i); - } - } else { - prev.StateAfter = next.StateAfter; - } - return; - } - break; - } - barriers.push(barrier); -} - pub(crate) fn transition( resource: &ID3D12Resource, before: D3D12_RESOURCE_STATES, @@ -2622,8 +6550,52 @@ fn pump() { } #[cfg(test)] -mod batch { - // Batch::texture_due lives here; `mod tests` is already taken at the top of this file +mod trail { + /// The trail keeps the newest things, and the report made when the + /// host device is removed says them and the pipeline library's state + /// (no card is asked for any of it). + #[test] + fn the_removal_report_says_the_newest_things_done() { + for n in 0..super::TRAIL_MOST + 5 { + super::trail(|| format!("thing {n} done")); + } + let text = super::removal_context(); + assert!(text.contains("the submitting thread was")); + assert!(text.contains("pipeline library: no call running")); + assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4))); + assert!(!text.contains("thing 4 done"), "the oldest entries are dropped"); + } +} + +#[cfg(test)] +mod spare { + use super::Spare; + + /// Kept things come back by size, the last given first, and nothing is + /// kept past the limit. + #[test] + fn kept_things_come_back_by_size_within_the_limit() { + let mut spare: Spare = Spare::new(); + assert_eq!(spare.take(4), None); + assert_eq!(spare.give(1, 4, 10), None); + assert_eq!(spare.give(2, 1, 10), None); + assert_eq!(spare.give(3, 4, 10), None); + assert_eq!(spare.bytes, 9); + // Past the limit: handed back, nothing changes. + assert_eq!(spare.give(4, 4, 10), Some(4)); + assert_eq!(spare.bytes, 9); + assert_eq!(spare.take(2), None, "no thing of that size"); + assert_eq!(spare.take(4), Some(3)); + assert_eq!(spare.take(4), Some(1)); + assert_eq!(spare.take(4), None); + assert_eq!(spare.take(1), Some(2)); + assert_eq!(spare.bytes, 0); + assert!(spare.kept.is_empty()); + } +} + +#[cfg(test)] +mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file use super::Batch; use std::sync::Arc; @@ -2694,56 +6666,40 @@ mod batch { before.as_secs_f64() / after.as_secs_f64() ); } -} - -#[cfg(test)] -mod title_memory_io { - use super::{copy_mapped, write_mapped}; - use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, - }; - - const PAGE: usize = 4096; - - /// Two committed pages followed by one reserved (not committed) page. - fn region() -> *mut u8 { - // SAFETY: a fresh reservation of ours, of which two pages are committed. - unsafe { - let base = VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_READWRITE); - assert!(!base.is_null()); - let committed = VirtualAlloc(base, 2 * PAGE, MEM_COMMIT, PAGE_READWRITE); - assert!(!committed.is_null()); - base.cast() - } - } - - fn release(base: *mut u8) { - // SAFETY: the reservation made by `region`. - unsafe { VirtualFree(base.cast(), 0, MEM_RELEASE) }; - } #[test] - fn write_mapped_writes_mapped_pages_and_skips_the_rest() { - let base = region(); - let data = vec![0xabu8; 3 * PAGE]; - // The third page is not committed: its piece is skipped, the others land. - write_mapped(base, data.as_ptr(), 3 * PAGE); - // SAFETY: the two committed pages of `region`. - let written = unsafe { std::slice::from_raw_parts(base, 2 * PAGE) }; - assert!(written.iter().all(|&b| b == 0xab)); - release(base); + fn vram_idle_ms_scales_with_pressure() { + use super::vram_idle_ms; + let gib = 1024 * 1024 * 1024; + // Normal (< 75%) + assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000); + assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000); + assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000); + // Moderate (75%..85%) + assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500); + assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500); + // High (>= 85%, including over-budget) + assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000); + assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000); + // Missing or zero budget falls back to normal + assert_eq!(vram_idle_ms(None), 5_000); + assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000); } #[test] - fn copy_into_title_memory_that_is_not_all_mapped_is_left_alone() { - let base = region(); - let from = vec![0x5au8; 3 * PAGE]; - copy_mapped(base, from.as_ptr(), 3 * PAGE, true); - // A whole copy into mapped memory works without asking the system first. - copy_mapped(base, from.as_ptr(), 2 * PAGE, true); - // SAFETY: the two committed pages of `region`. - let now = unsafe { std::slice::from_raw_parts(base, 2 * PAGE) }; - assert!(now.iter().all(|&b| b == 0x5a)); - release(base); + fn ram_idle_ms_scales_with_pressure() { + use super::ram_idle_ms; + let gib = 1024 * 1024 * 1024; + // Normal (>= 4 GiB) + assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000); + assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000); + // Moderate (2 GiB..4 GiB) + assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000); + assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000); + // High (< 2 GiB) + assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000); + assert_eq!(ram_idle_ms(Some(0)), 2_000); + // Missing falls back to normal + assert_eq!(ram_idle_ms(None), 10_000); } } diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 3b980da..85eaf91 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -2,15 +2,18 @@ //! title's own compute passes write most of them; a pass we drop or //! translate wrongly leaves whatever the memory held, and a draw of four //! billion vertices or a dispatch past the host's limits runs until the -//! host resets the display driver. So every record is clamped on the GPU, -//! just before its execution, by a compute shader of ours (HLSL compiled by -//! the system's compiler as a 5.1 shader; its root signature is built here, -//! since Wine's compiler does not embed one). +//! host resets the display driver. So active records are copied and clamped +//! on the GPU into a device-local scratch buffer, just before execution, by a +//! compute shader of ours (HLSL compiled by the system's compiler; a 5.1 +//! shader with its root signature inside), leaving the title's argument and +//! count buffers untouched. //! -//! Each list also has a budget (2^27 vertex instances or threads, groups -//! counted as 64 threads, mesh groups as 128): records past it run empty, -//! so a list of thousands of garbage records cannot run for seconds -//! either. +//! When a count buffer is given, threads at or past `min(max, count)` return +//! immediately without charging the list's budget or reading uninitialized +//! tail slots. Each list has a budget (2^27 vertex instances or threads, +//! groups counted as 64 threads, mesh groups as 128): active records past it +//! run empty, saturating without 32-bit wraparound so a list of thousands of +//! garbage records cannot run for seconds either. //! //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 //! groups per dimension and 2^20 per dispatch, one-dimensional mesh @@ -24,190 +27,111 @@ use windows::core::s; use crate::host::{HostList, host, transition}; -// Written for both compilers `D3DCompile` may be: Microsoft's and, under -// Wine, vkd3d-shader's, which has no `RWByteAddressBuffer` methods. So the -// buffers are structured buffers of words (a root UAV takes either). const SOURCE: &str = r#" -cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; -RWStructuredBuffer args : register(u0); +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { + uint kind; + uint stride; + uint records; + uint args_offset; + // Bit 0: a count buffer bounds the records. Bit 1: the records are a + // window clamped ahead of their draws: one that asks for more than can + // run is left empty and costs nothing. + uint has_count; + uint count_offset; +}; +ByteAddressBuffer src_args : register(t0); +ByteAddressBuffer count_buf : register(t1); +RWByteAddressBuffer dst_args : register(u0); // The list's work so far (vertex instances, threads): past the budget, // records run empty. -RWStructuredBuffer budget : register(u1); +RWByteAddressBuffer budget : register(u1); static const uint BUDGET = 1u << 27; // Groups of one dispatch; more run empty. static const uint GROUPS = 1u << 20; +[RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { - if (id.x >= records) return; - uint at = id.x * (stride / 4); + uint eff_count = records; + bool ahead = (has_count & 2u) != 0; + if ((has_count & 1u) != 0) { + eff_count = min(eff_count, count_buf.Load(count_offset)); + } + if (id.x >= eff_count) return; + uint src_at = args_offset + id.x * stride; + uint dst_at = id.x * stride; uint cost; + uint2 draw_counts = uint2(0, 0); + uint3 groups = uint3(0, 0, 0); if (kind <= 1) { // Draws: vertex or index count, then instances. - uint count = min(args[at], 1u << 24); - uint instances = min(args[at + 1], (1u << 26) / max(count, 1u)); + uint2 asked = src_args.Load2(src_at); + if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) { + asked = uint2(0, 0); + } + uint count = min(asked.x, 1u << 24); + uint instances = min(asked.y, (1u << 26) / max(count, 1u)); cost = count * instances; - args[at] = count; - args[at + 1] = instances; + draw_counts = uint2(count, instances); } else if (kind == 2) { - uint3 g = min(uint3(args[at], args[at + 1], args[at + 2]), uint3(65535, 65535, 65535)); + uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); // x * y fits 32 bits; the whole count may not. if (g.z != 0 && g.x * g.y > GROUPS / g.z) { g = uint3(0, 0, 0); } - cost = g.x * g.y * g.z * 64; - args[at] = g.x; - args[at + 1] = g.y; - args[at + 2] = g.z; + cost = g.x * g.y * g.z * 64u; + groups = g; } else { // Mesh dispatches: the console's are one-dimensional. - uint3 g = uint3(min(args[at], 65535u), min(args[at + 1], 1u), min(args[at + 2], 1u)); - cost = g.x * g.y * g.z * 128; - args[at] = g.x; - args[at + 1] = g.y; - args[at + 2] = g.z; - } - uint before; - InterlockedAdd(budget[0], cost, before); - if (before >= BUDGET || before + cost > BUDGET) { - // Draws keep their layout with no vertices; groups become zero. - args[at] = 0; - } -} -"#; - -/// Where `dxcompiler.dll` is looked for: `VICTORY_DXC` (the DLL or its -/// folder), beside the `dxil.dll` shader validation uses (the SDK ships them -/// together), then the executable's folder and System32. -fn dxc_library() -> windows::core::Result { - use windows::Win32::System::LibraryLoader::{ - LOAD_LIBRARY_SEARCH_APPLICATION_DIR, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, - LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW, - }; - use windows::core::{HSTRING, w}; - let mut paths: Vec = Vec::new(); - if let Some(p) = std::env::var_os("VICTORY_DXC").map(std::path::PathBuf::from) { - paths.push(if p.is_dir() { - p.join("dxcompiler.dll") - } else { - p - }); - } - if let Some(dir) = victory_shader::emit::validator::Validator::default_path() - .and_then(|p| p.parent().map(|d| d.to_path_buf())) - { - paths.push(dir.join("dxcompiler.dll")); - } - for path in paths.iter().filter(|p| p.is_file()) { - // SAFETY: a NUL-terminated path; its folder (dxil.dll) is searched first. - if let Ok(m) = unsafe { - LoadLibraryExW( - &HSTRING::from(path.as_path()), - None, - LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, - ) - } { - return Ok(m); + uint3 g = src_args.Load3(src_at); + // Ahead of its draw, a record over the most a dispatch runs is a + // slot the title has not filled (the title leaves all + // ones there): empty, and not counted below either. + if (ahead && g.x > 65535u) { + g = uint3(0, 0, 0); } + // Diagnostics, in the budget buffer's next words: the largest + // group count a mesh record asked for, and the groups asked in all. + uint was; + budget.InterlockedMax(4, g.x, was); + budget.InterlockedAdd(8, min(g.x, 1u << 24), was); + g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); + cost = g.x * g.y * g.z * 128u; + groups = g; } - // SAFETY: a bare name, searched only in the executable's folder and System32. - unsafe { - LoadLibraryExW( - w!("dxcompiler.dll"), - None, - LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32, - ) - } -} - -/// Compiles a compute shader with DXC (see [`dxc_library`]). -fn dxc_compile(source: &str) -> windows::core::Result> { - use windows::Win32::Graphics::Direct3D::Dxc::*; - use windows::Win32::System::LibraryLoader::GetProcAddress; - use windows::core::{Interface, w}; - type Create = unsafe extern "system" fn( - *const windows::core::GUID, - *const windows::core::GUID, - *mut *mut std::ffi::c_void, - ) -> windows::core::HRESULT; - // SAFETY: loading the compiler and calling its documented entry point with - // out pointers of ours; the buffer and arguments outlive the calls. - unsafe { - let library = dxc_library()?; - let create: Create = std::mem::transmute( - GetProcAddress(library, s!("DxcCreateInstance")) - .ok_or_else(windows::core::Error::from_thread)?, - ); - let mut raw = std::ptr::null_mut(); - create(&CLSID_DxcCompiler, &IDxcCompiler3::IID, &mut raw).ok()?; - let compiler = IDxcCompiler3::from_raw(raw); - let buffer = DxcBuffer { - Ptr: source.as_ptr().cast(), - Size: source.len(), - Encoding: DXC_CP_UTF8.0, - }; - let arguments = [w!("-T"), w!("cs_6_0"), w!("-E"), w!("main"), w!("-O3")]; - let result: IDxcResult = compiler.Compile(&buffer, Some(&arguments), None)?; - if let Err(e) = result.GetStatus()?.ok() { - if let Ok(errors) = result.GetErrorBuffer() { - let text = std::slice::from_raw_parts( - errors.GetBufferPointer().cast::(), - errors.GetBufferSize(), - ); - tracing::warn!( - "argument clamp: DXC: {}", - String::from_utf8_lossy(text).trim() - ); - } - return Err(e); - } - let blob = result.GetResult()?; - let mut bytes = - std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()) - .to_vec(); - sign_dxc_bytecode(library, &mut bytes)?; - Ok(bytes) + bool over = false; + if (cost > 0) { + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost); + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + over = before >= BUDGET || BUDGET - before < cost; } -} - -/// Older DXC DLLs can compile successfully without finding the signing DLL. -/// The resulting container has a zero digest and native D3D12 rejects it. -fn sign_dxc_bytecode( - compiler: windows::Win32::Foundation::HMODULE, - bytes: &mut [u8], -) -> windows::core::Result<()> { - use std::os::windows::ffi::OsStringExt; - use victory_shader::emit::validator::Validator; - use windows::Win32::Foundation::E_FAIL; - use windows::Win32::System::LibraryLoader::GetModuleFileNameW; - - if bytes - .get(4..20) - .is_some_and(|digest| digest.iter().any(|&b| b != 0)) - { - return Ok(()); + if (kind <= 1) { + if (over) { + draw_counts = uint2(0, 0); + } + dst_args.Store2(dst_at, draw_counts); + for (uint off = 8; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } + } else { + if (over) { + groups = uint3(0, 0, 0); + } + dst_args.Store3(dst_at, groups); + for (uint off = 12; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } } - - let explicit = std::env::var_os("VICTORY_DXIL").map(std::path::PathBuf::from); - let beside_compiler = || { - let mut path = vec![0; 32_768]; - // SAFETY: the compiler module is loaded and the buffer is ours. - let len = unsafe { GetModuleFileNameW(Some(compiler), &mut path) } as usize; - if len == 0 || len >= path.len() { - return None; - } - let compiler = std::path::PathBuf::from(std::ffi::OsString::from_wide(&path[..len])); - let validator = compiler.with_file_name("dxil.dll"); - validator.is_file().then_some(validator) - }; - let path = explicit - .or_else(beside_compiler) - .or_else(Validator::default_path); - Validator::load(path.as_deref()) - .and_then(|mut validator| validator.validate(bytes)) - .map_err(|error| { - windows::core::Error::new(E_FAIL, format!("cannot sign DXC shader: {error}")) - }) } +"#; struct Clamp { root: ID3D12RootSignature, @@ -234,6 +158,10 @@ fn clamp() -> Option<&'static Clamp> { fn make() -> windows::core::Result { let device = &host().ok_or_else(windows::core::Error::empty)?.device; + make_for(device) +} + +fn make_for(device: &ID3D12Device) -> windows::core::Result { let mut code: Option = None; let mut errors: Option = None; // SAFETY: the source and names live through the call; out pointers ours. @@ -252,12 +180,8 @@ fn make() -> windows::core::Result { Some(&mut errors), ) }; - // Wine's d3dcompiler_47 (vkd3d-shader) rejects RWByteAddressBuffer loads: - // then DXC (dxcompiler.dll; see `dxc_library` for where it is looked for) compiles - // the same source as cs_6_0, root signature inside. - let fallback; - if let Err(e) = &compiled { - if let Some(errors) = &errors { + if let Err(e) = compiled { + if let Some(errors) = errors { // SAFETY: the blob's own bytes. let text = unsafe { std::slice::from_raw_parts( @@ -265,26 +189,16 @@ fn make() -> windows::core::Result { errors.GetBufferSize(), ) }; - tracing::info!(error = %e, "argument clamp: the system compiler refused it ({}); trying DXC", String::from_utf8_lossy(text).trim()); + tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text)); } - fallback = dxc_compile(SOURCE) - .inspect_err(|e| tracing::warn!(error = %e, "argument clamp: DXC failed too"))?; - } else { - fallback = Vec::new(); + return Err(e); } - // SAFETY: the blob's own bytes; the DXC fallback carries its root - // signature inside the shader. + let code = code.ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob's own bytes; the root signature is inside the shader. unsafe { - let (bytes, root) = match &code { - Some(code) => ( - std::slice::from_raw_parts( - code.GetBufferPointer().cast::(), - code.GetBufferSize(), - ), - root_signature(device)?, - ), - None => (&fallback[..], device.CreateRootSignature(0, &fallback[..])?), - }; + let bytes = + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: D3D12_SHADER_BYTECODE { @@ -297,104 +211,199 @@ fn make() -> windows::core::Result { } } -/// Constants b0 (four words: kind, stride, records, unused), then the -/// arguments as root UAV u0 and the budget as root UAV u1. -fn root_signature(device: &ID3D12Device) -> windows::core::Result { - let uav = |register| D3D12_ROOT_PARAMETER { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, - Anonymous: D3D12_ROOT_PARAMETER_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR { - ShaderRegister: register, - RegisterSpace: 0, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }; - let params = [ - D3D12_ROOT_PARAMETER { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, - Anonymous: D3D12_ROOT_PARAMETER_0 { - Constants: D3D12_ROOT_CONSTANTS { - ShaderRegister: 0, - RegisterSpace: 0, - Num32BitValues: 4, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }, - uav(0), - uav(1), - ]; - let desc = D3D12_ROOT_SIGNATURE_DESC { - NumParameters: params.len() as u32, - pParameters: params.as_ptr(), - NumStaticSamplers: 0, - pStaticSamplers: std::ptr::null(), - Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, - }; - // SAFETY: the description points at a live array; the blob is read in - // full before it is released. - unsafe { - let mut blob: Option = None; - D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None)?; - let blob = blob.ok_or_else(windows::core::Error::empty)?; - let bytes = - std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()); - device.CreateRootSignature(0, bytes) +/// Minimum record byte stride for a supported PC indirect argument `kind`. +fn min_stride(kind: u32) -> Option { + match kind { + 0 => Some(16), + 1 => Some(20), + 2 | 10 => Some(12), + _ => None, + } +} + +/// Validates record alignment and returns the scratch byte size `stride * records`. +fn validate_layout( + (kind, stride, records): (u32, u32, u32), + src_offset: u64, + count_offset: Option, +) -> Option { + let min = min_stride(kind)?; + if stride < min || !stride.is_multiple_of(4) || !src_offset.is_multiple_of(4) { + return None; } + if count_offset.is_some_and(|off| !off.is_multiple_of(4)) { + return None; + } + let bytes = u64::from(stride).checked_mul(u64::from(records))?; + (bytes <= u64::from(u32::MAX)).then_some(bytes) } -/// 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. +/// Records, in `list`, the non-destructive clamp of up to `records` records of +/// `kind` (PC argument numbering) `stride` bytes apart from `src` (and bounded +/// by the 32-bit count in `count` when given) into a device-local scratch +/// buffer, leaving that scratch buffer in `INDIRECT_ARGUMENT` at offset `0`. +/// Replaces the list's compute root signature and pipeline (callers bind +/// theirs after). `None` if the clamp or alignment is not available. pub(crate) fn bound( list: &HostList, - buffer: &ID3D12Resource, - gpu: u64, + src: (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + spec: (u32, u32, u32), +) -> Option { + let bytes = validate_layout(spec, src.1, count.map(|(_, off)| off))?; + let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?); + record_clamp(c, &list.list, &dst, budget, src, count, spec).then_some(dst) +} + +/// [`bound`] for a window of records clamped ahead of the draws that will +/// read them (`crate::draw`'s windows; no count buffer). The records past +/// the ones the title filled are whatever the buffer holds, and each +/// record clamped charges the list's budget when it is clamped: a slot of +/// all ones, clamped to the most a mesh dispatch runs (65,535 groups), +/// charged a sixteenth of the budget, so sixteen of them emptied every +/// draw of the list after them (run 93: "the largest group count asked for +/// 4294967295", 43 to 153 such records a frame). Here a record that asks +/// for more than can run is left empty and charges nothing; a record +/// clamped alone is clamped and charged as before. +pub(crate) fn bound_ahead( + list: &HostList, + src: (&ID3D12Resource, u64), + spec: (u32, u32, u32), +) -> Option { + let bytes = validate_layout(spec, src.1, None)?; + let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?); + record_clamp_as(c, &list.list, &dst, budget, src, None, spec, true).then_some(dst) +} + +fn record_clamp( + c: &Clamp, + l: &ID3D12GraphicsCommandList, + dst: &ID3D12Resource, + budget: u64, + src: (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + spec: (u32, u32, u32), +) -> bool { + record_clamp_as(c, l, dst, budget, src, count, spec, false) +} + +/// [`record_clamp`]; `ahead`: the records are a window clamped ahead of +/// their draws ([`bound_ahead`]). +#[allow(clippy::too_many_arguments)] +fn record_clamp_as( + c: &Clamp, + l: &ID3D12GraphicsCommandList, + dst: &ID3D12Resource, + budget: u64, + (src, src_offset): (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, (kind, stride, records): (u32, u32, u32), + ahead: bool, ) -> bool { - let (Some(c), Some(budget)) = (clamp(), list.budget()) else { + let Some(bytes) = validate_layout( + (kind, stride, records), + src_offset, + count.map(|(_, off)| off), + ) else { return false; }; - if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) { + // SAFETY: live D3D12 buffer resources. + let (src_base, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress()) }; + if !src_base.is_multiple_of(4) || !dst_gpu.is_multiple_of(4) || !budget.is_multiple_of(4) { return false; } - 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. + let (src_gpu, args_offset) = match src_offset + .checked_add(bytes) + .filter(|&end| end <= u64::from(u32::MAX)) + { + Some(_) => (src_base, src_offset as u32), + None => { + let Some(rebased) = src_base.checked_add(src_offset) else { + return false; + }; + (rebased, 0) + } + }; + let (count_gpu, has_count, count_offset) = match count { + Some((buf, off)) => { + // SAFETY: a live D3D12 buffer resource. + let base = unsafe { buf.GetGPUVirtualAddress() }; + if !base.is_multiple_of(4) { + return false; + } + match off.checked_add(4).filter(|&end| end <= u64::from(u32::MAX)) { + Some(_) => (base, 1u32, off as u32), + None => { + let Some(rebased) = base.checked_add(off) else { + return false; + }; + (rebased, 1u32, 0u32) + } + } + } + None => (src_gpu, 0u32, 0u32), + }; + let constants = [kind, stride, records, args_offset, has_count | (u32::from(ahead) << 1), count_offset]; + // SAFETY: an open list; our root signature and pipeline; live source, + // count, scratch destination, and budget buffers. `src` and `count` stay + // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst` + // transitions `COMMON -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`. + // Diagnostics: counted; `VICTORY_BARRIER_TEST=indirect` leaves the two + // waits for every earlier shader write out (the state changes stay). + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::IndirectBounded, 1); + #[cfg(feature = "diagnostics")] + let waits = crate::copystat::barrier_test() & 2 == 0; + #[cfg(not(feature = "diagnostics"))] + let waits = true; + let first = [ + uav_barrier(), + transition( + dst, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + ]; + let second = [ + uav_barrier(), + transition( + dst, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + ), + ]; + let skip = usize::from(!waits); unsafe { - // Earlier shader writes (the title's argument passes) first. - l.ResourceBarrier(&[uav_barrier()]); - l.SetComputeRootSignature(&c.root); - l.SetPipelineState(&c.pso); - l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - l.SetComputeRootUnorderedAccessView(1, gpu); - l.SetComputeRootUnorderedAccessView(2, budget); - l.Dispatch(records.div_ceil(64), 1, 1); - l.ResourceBarrier(&[ - uav_barrier(), - transition( - buffer, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - ), - ]); + // Earlier shader writes (the title's argument and count passes) first. + l.ResourceBarrier(&first[skip..]); + if records > 0 { + l.SetComputeRootSignature(&c.root); + l.SetPipelineState(&c.pso); + l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + l.SetComputeRootShaderResourceView(1, src_gpu); + l.SetComputeRootShaderResourceView(2, count_gpu); + l.SetComputeRootUnorderedAccessView(3, dst_gpu); + l.SetComputeRootUnorderedAccessView(4, budget); + l.Dispatch(records.div_ceil(64), 1, 1); + } + l.ResourceBarrier(&second[skip..]); } true } -/// 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) { - // SAFETY: an open list and a live buffer. +/// After indirect execution (or if preparation failed after [`bound`]): +/// returns the scratch buffer to the common state for the next call. +pub(crate) fn done(list: &HostList, scratch: &ID3D12Resource) { + done_on(&list.list, scratch); +} + +fn done_on(list: &ID3D12GraphicsCommandList, scratch: &ID3D12Resource) { + // SAFETY: an open list and a live scratch buffer in INDIRECT_ARGUMENT. unsafe { - list.list.ResourceBarrier(&[transition( - buffer, + list.ResourceBarrier(&[transition( + scratch, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COMMON, )]) }; } @@ -413,6 +422,304 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { #[cfg(test)] mod tests { + use super::*; + use windows::Win32::Foundation::HANDLE; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::Interface; + + const WORKER_CS: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer hits : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint prev; + hits.InterlockedAdd(0, 1, prev); +} +"#; + + struct WarpHarness { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + clamp: Clamp, + worker: Clamp, + } + + impl WarpHarness { + fn new() -> Option { + // SAFETY: plain DXGI WARP query and D3D12 test harness setup. + unsafe { + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let desc = adapter.cast::().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + let clamp = make_for(&device).expect("clamp shader must compile on WARP"); + let worker = compile_cs(&device, WORKER_CS).expect("worker shader must compile"); + Some(Self { + device, + queue, + allocator, + list, + fence, + submitted: 0, + event, + clamp, + worker, + }) + } + } + + /// CPU-mapped L0 write-back buffer matching `Shadow`'s heap type. + fn shared_buffer(&self, size: u64) -> (ID3D12Resource, *mut u8, u64) { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(4), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain buffer creation and persistent CPU mapping. + unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .unwrap(); + let buffer = buffer.unwrap(); + buffer.Map(0, None, Some(&mut data)).unwrap(); + let gpu = buffer.GetGPUVirtualAddress(); + (buffer, data.cast(), gpu) + } + } + + /// Device-local `DEFAULT`-heap UAV scratch buffer. + fn default_uav(&self, size: u64) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(64 << 10), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain device-local buffer creation. + unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .unwrap(); + } + buffer.unwrap() + } + + fn signature(&self, kind: u32, stride: u32) -> ID3D12CommandSignature { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: stride, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + // SAFETY: valid single-argument command signature description. + unsafe { + self.device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + } + sig.unwrap() + } + + fn submit_and_wait(&mut self) { + self.submitted += 1; + // SAFETY: closing, executing, waiting on fence, and resetting our list. + unsafe { + self.list.Close().unwrap(); + let cmd: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(cmd)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence + .SetEventOnCompletion(self.submitted, self.event) + .unwrap(); + WaitForSingleObject(self.event, INFINITE); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + } + + fn compile_cs(device: &ID3D12Device, source: &str) -> windows::core::Result { + let mut code: Option = None; + // SAFETY: source and entry names outlive `D3DCompile`. + unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + s!("worker"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + let code = code.unwrap(); + let bytes = std::slice::from_raw_parts( + code.GetBufferPointer().cast::(), + code.GetBufferSize(), + ); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; + let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok(Clamp { root, pso }) + } + } + + /// The compare of copies in the card's memory (`crate::host`), on the + /// software adapter. Told 1 it flags the pieces whose bytes are not + /// what was hashed last and leaves the hashes: a piece a shader changed + /// and a later one changed back then looks untouched, which is right + /// only if the piece was fetched after both. Told 2 (submissions sent + /// ahead with the relay, whose pieces are fetched flight by flight) it + /// stores the hash it made: each compare flags what changed since the + /// compare before it, also a change back. + #[test] + fn warp_card_compare_stores_the_hash_it_made_when_told() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP"); + const PIECE: usize = 64 << 10; + const PIECES: u32 = 3; + let size = PIECE * PIECES as usize; + let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64); + let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES)); + let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64); + let content: Vec = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + // SAFETY: the mapping holds `size` bytes. + unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) }; + // One pass over the three pieces; what it left in `differs` (7s + // where it stored nothing). + let run = |warp: &mut WarpHarness, mode: u32| -> [u32; 3] { + // SAFETY: our open list, live buffers, the compare's own root + // signature; the mappings hold what is read and written. + unsafe { + for piece in 0..PIECES as usize { + differs_ptr.cast::().add(piece).write_volatile(7); + } + warp.list.SetComputeRootSignature(&compare.root); + warp.list.SetPipelineState(&compare.pso); + let constants = [0u32, 0, size as u32, PIECES, 0, mode]; + warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootShaderResourceView(1, now_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); + warp.list.Dispatch(PIECES.div_ceil(64), 1, 1); + } + warp.submit_and_wait(); + // SAFETY: as above. + [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::().add(piece).read_volatile() }) + }; + let at = PIECE + 1234; + // SAFETY (each): inside the mapping. + let set = |value: u8| unsafe { now_ptr.add(at).write_volatile(value) }; + // 0: the hashes are stored, nothing is flagged. + assert_eq!(run(&mut warp, 0), [7, 7, 7]); + assert_eq!(run(&mut warp, 1), [0, 0, 0]); + // A change in the second piece: flagged, and with 1 flagged again + // (the hash stays the old one). + set(content[at] ^ 0x40); + assert_eq!(run(&mut warp, 1), [0, 1, 0]); + assert_eq!(run(&mut warp, 1), [0, 1, 0]); + // Changed back: with 1 the piece looks untouched. + set(content[at]); + assert_eq!(run(&mut warp, 1), [0, 0, 0]); + // With 2 the change is flagged once, and the hash is the new one. + set(content[at] ^ 0x40); + assert_eq!(run(&mut warp, 2), [0, 1, 0]); + assert_eq!(run(&mut warp, 2), [0, 0, 0]); + // Changed back: flagged, where 1 saw nothing. + set(content[at]); + assert_eq!(run(&mut warp, 2), [0, 1, 0]); + assert_eq!(run(&mut warp, 2), [0, 0, 0]); + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { @@ -422,79 +729,1089 @@ mod tests { assert!(super::clamp().is_some()); } - /// The clamp bounds a draw, a dispatch and a mesh dispatch on the GPU. #[test] - fn arguments_are_clamped_on_the_gpu() { - clamp_on_the_gpu(false); + fn rejects_unaligned_or_undersized_layouts() { + assert_eq!(validate_layout((0, 16, 4), 0, None), Some(64)); + assert_eq!(validate_layout((1, 20, 4), 64, Some(128)), Some(80)); + assert_eq!(validate_layout((2, 12, 0), 0, Some(0)), Some(0)); + assert_eq!(validate_layout((10, 16, 2), 8, None), Some(32)); + // Undersized strides for each kind. + assert_eq!(validate_layout((0, 12, 1), 0, None), None); + assert_eq!(validate_layout((1, 16, 1), 0, None), None); + assert_eq!(validate_layout((2, 8, 1), 0, None), None); + assert_eq!(validate_layout((10, 8, 1), 0, None), None); + // Unknown kind. + assert_eq!(validate_layout((3, 16, 1), 0, None), None); + // Unaligned stride, source offset, or count offset. + assert_eq!(validate_layout((0, 18, 1), 0, None), None); + assert_eq!(validate_layout((0, 16, 1), 2, None), None); + assert_eq!(validate_layout((0, 16, 1), 0, Some(6)), None); + // Total byte size exceeding 32-bit ByteAddressBuffer indexing. + assert_eq!(validate_layout((1, 20, u32::MAX), 0, None), None); } - /// The same in a list with the title's kind of descriptor heaps bound - /// (under vkd3d-proton the clamp then faulted on address 0). + /// WARP D3D12 execution test proving: + /// (a) `countBuffer` with a small count (`3`) and `4,093` garbage tail slots + /// (`max = 4096`) does NOT blow `BUDGET` or zero valid dispatches in + /// this or subsequent `ExecuteIndirect` calls in the same list, + /// (b) `src_args` (and `count_buf`) are NOT mutated in-place, and + /// (c) full `stride` bytes (`stride = 24` > `12`) are copied for active + /// records into `dst_args` at offset `0`. #[test] - fn arguments_are_clamped_with_heaps_bound() { - clamp_on_the_gpu(true); + fn warp_count_buffer_ignores_garbage_tail_and_preserves_source() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 24; // 6 dwords: 3 dispatch group counts + 3 extra payload dwords + const MAX: u32 = 4096; + const ARGS_OFFSET: usize = 64; // non-zero offset with sentinel prefix + const COUNT_OFFSET_1: usize = 128; + const COUNT_OFFSET_2: usize = 192; + + let src_bytes = ARGS_OFFSET + (STRIDE as usize) * (MAX as usize) + 64; + let (src_buf, src_ptr, _) = warp.shared_buffer(src_bytes as u64); + let (count_buf, count_ptr, _) = warp.shared_buffer(512); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer((STRIDE * 8) as u64); + let dst_buf = warp.default_uav(u64::from(STRIDE) * u64::from(MAX)); + let sig = warp.signature(KIND_DISPATCH, STRIDE); + + // Fill the entire source buffer with non-zero sentinel bytes, then + // populate 3 valid records at `ARGS_OFFSET` and 4,093 huge garbage + // records in `3..MAX` that would exhaust `BUDGET` ~2,000x over if read. + let mut initial_src = vec![0xA5u8; src_bytes]; + let write_record = |buf: &mut [u8], idx: usize, words: [u32; 6]| { + let base = ARGS_OFFSET + idx * (STRIDE as usize); + for (w, val) in words.into_iter().enumerate() { + buf[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes()); + } + }; + write_record( + &mut initial_src, + 0, + [3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666], + ); + write_record( + &mut initial_src, + 1, + [5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC], + ); + // Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1). + write_record( + &mut initial_src, + 2, + [100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567], + ); + for slot in 3..MAX as usize { + // Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups + // (`cost = 67,107,840 ~= BUDGET / 2`), exhausting `BUDGET` immediately! + write_record( + &mut initial_src, + slot, + [0xFFFF_FFFF, 16, 1, 0xDEAD_BEEF, 0xBAD0_C0DE, slot as u32], + ); + } + + // Second indirect call's source records (at offset 0 of a second buffer, + // or later in `count_buf`): put 2 active records + garbage tail in a + // second range to run back-to-back in the SAME command list. + let mut initial_count = vec![0x5Au8; 512]; + initial_count[COUNT_OFFSET_1..COUNT_OFFSET_1 + 4].copy_from_slice(&3u32.to_le_bytes()); + initial_count[COUNT_OFFSET_2..COUNT_OFFSET_2 + 4].copy_from_slice(&2u32.to_le_bytes()); + + // SAFETY: buffers are mapped with exact capacities above. + unsafe { + std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, src_bytes); + std::ptr::copy_nonoverlapping(initial_count.as_ptr(), count_ptr, 512); + (budget_ptr as *mut u32).write_volatile(0); + (hits_ptr as *mut u32).write_volatile(0); + std::ptr::write_bytes(readback_ptr, 0, (STRIDE * 8) as usize); + } + + // Record Call #1 (`eff_count = 3` out of `MAX = 4096`), copy the first + // 5 records of `dst_buf` out for inspection, then record Call #2 + // (`eff_count = 2` out of `MAX = 4096`) reusing `dst_buf` in the same list! + assert!(record_clamp( + &warp.clamp, + &warp.list, + &dst_buf, + budget_gpu, + (&src_buf, ARGS_OFFSET as u64), + Some((&count_buf, COUNT_OFFSET_1 as u64)), + (KIND_DISPATCH, STRIDE, MAX), + )); + // SAFETY: open command list, valid worker PSO/root and buffers. + unsafe { + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + warp.list.ExecuteIndirect( + &sig, + MAX, + &dst_buf, + 0, + Some(&count_buf), + COUNT_OFFSET_1 as u64, + ); + } + done_on(&warp.list, &dst_buf); + + // Snapshot `dst_buf` after Call #1 (from `COMMON`, copy 5 * STRIDE bytes, + // then return `dst_buf` to `COMMON` before Call #2). + // SAFETY: open command list; `dst_buf` returned to `COMMON` by `done_on`. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list + .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, u64::from(STRIDE * 5)); + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + + // Call #2 in the SAME command list (`eff_count = 2` -> records 0 and 1: + // 6 + 5 = 11 groups). Would run empty if Call #1's tail blew `BUDGET`! + assert!(record_clamp( + &warp.clamp, + &warp.list, + &dst_buf, + budget_gpu, + (&src_buf, ARGS_OFFSET as u64), + Some((&count_buf, COUNT_OFFSET_2 as u64)), + (KIND_DISPATCH, STRIDE, MAX), + )); + // SAFETY: open command list, valid worker PSO/root and buffers. + unsafe { + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + warp.list.ExecuteIndirect( + &sig, + MAX, + &dst_buf, + 0, + Some(&count_buf), + COUNT_OFFSET_2 as u64, + ); + } + done_on(&warp.list, &dst_buf); + + warp.submit_and_wait(); + + // SAFETY: GPU execution finished; read mapped host results. + let (hits, spent, after_src, after_count, clamped_words) = unsafe { + let hits = (hits_ptr as *const u32).read_volatile(); + let spent = (budget_ptr as *const u32).read_volatile(); + let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), src_bytes).to_vec(); + let after_count = std::slice::from_raw_parts(count_ptr.cast_const(), 512).to_vec(); + let words = std::slice::from_raw_parts( + readback_ptr.cast::().cast_const(), + (STRIDE as usize / 4) * 5, + ) + .to_vec(); + (hits, spent, after_src, after_count, words) + }; + + // Call #1: (3*2*1) + (5*1*1) + (65535*1*1) = 65,546 groups. + // Call #2: (3*2*1) + (5*1*1) = 11 groups. + let expected_groups = (6 + 5 + 65_535) + (6 + 5); + assert_eq!( + hits, expected_groups, + "valid indirect dispatches must all execute" + ); + assert_eq!( + spent, + expected_groups * 64, + "budget must reflect only active records below countBuffer" + ); + assert_eq!( + after_src, initial_src, + "src_args must never be mutated in-place" + ); + assert_eq!( + after_count, initial_count, + "count_buf must never be mutated" + ); + + // Check `dst_args` records 0..3: clamped group counts + preserved extra stride words. + assert_eq!( + &clamped_words[0..6], + &[3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666] + ); + assert_eq!( + &clamped_words[6..12], + &[5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC] + ); + assert_eq!( + &clamped_words[12..18], + &[65_535, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567] + ); + // Inactive slot 3 was never copied from `src_args`. + assert_ne!(clamped_words[21], 0xDEAD_BEEF); } - fn clamp_on_the_gpu(heaps: bool) { - use super::*; - let Some(host) = host() else { - return; // no host GPU here + /// WARP D3D12 test proving `BUDGET` saturates without 32-bit unsigned + /// wraparound across >64 huge indexed-draw records (`count = None`), while + /// preserving `StartIndexLocation`, `BaseVertexLocation`, + /// `StartInstanceLocation`, and custom stride padding, and leaving + /// `src_args` untouched. + /// A window of mesh records clamped ahead: the filled ones come out as + /// they are and are charged, the slots of all ones come out empty and + /// charge nothing; clamped as single records the same slots are clamped + /// to the most and spend the budget. + #[test] + fn warp_window_leaves_unfilled_slots_empty_and_uncharged() { + let Some(mut warp) = WarpHarness::new() else { + return; }; - let (buffer, data) = host.shared_buffer(256).unwrap(); - let words = data.cast::(); - let records: [(usize, [u32; 4]); 3] = [ - (0, [u32::MAX, 5, 0, 0]), // draw: vertices, instances - (16, [70_000, 2, 3, 0]), // dispatch - (32, [100_000, 7, 9, 0]), // mesh dispatch - ]; - for (at, w) in records { - // SAFETY: inside the mapped 256 bytes. - unsafe { std::ptr::copy_nonoverlapping(w.as_ptr(), words.add(at / 4), 4) }; - } - let list = host.new_list().unwrap(); - if heaps { - let heap = |kind, count| -> ID3D12DescriptorHeap { - // SAFETY: plain heap creation. - unsafe { - host.device - .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: count, - Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, - NodeMask: 0, - }) - } - .unwrap() - }; - let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1024); - let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 16); - // SAFETY: an open list and shader-visible heaps it keeps alive. + const KIND_MESH: u32 = 10; + const STRIDE: u32 = 32; + const RECORDS: u32 = 16; + let filled = [5u32, 0, 519]; + let total = (STRIDE * RECORDS) as usize; + let mut src = vec![0xffu8; total]; + for (i, groups) in filled.into_iter().enumerate() { + let words = [groups, 1, 1, 0xAB00 + i as u32]; + for (w, word) in words.into_iter().enumerate() { + let at = i * STRIDE as usize + w * 4; + src[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + } + for ahead in [true, false] { + let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64); + let dst_buf = warp.default_uav(total as u64); + // SAFETY: mapped buffers of these sizes. + unsafe { + std::ptr::copy_nonoverlapping(src.as_ptr(), src_ptr, total); + std::ptr::write_bytes(budget_ptr, 0, 256); + std::ptr::write_bytes(readback_ptr, 0, total); + } + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + &dst_buf, + budget_gpu, + (&src_buf, 0), + None, + (KIND_MESH, STRIDE, RECORDS), + ahead, + )); + done_on(&warp.list, &dst_buf); + // SAFETY: an open list; the scratch buffer is copied for the check. unsafe { - list.list - .SetDescriptorHeaps(&[Some(views.clone()), Some(samplers.clone())]) + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (spent, largest, out) = unsafe { + ( + (budget_ptr as *const u32).read_volatile(), + (budget_ptr as *const u32).add(1).read_volatile(), + std::slice::from_raw_parts(readback_ptr.cast::().cast_const(), total / 4).to_vec(), + ) }; - list.keep(&views); - list.keep(&samplers); + for (i, groups) in filled.into_iter().enumerate() { + let rec = &out[i * 8..i * 8 + 4]; + assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}"); + } + let charged_filled = (5 + 519) * 128; + if ahead { + for i in filled.len()..RECORDS as usize { + assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty"); + assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are"); + } + assert_eq!(spent, charged_filled, "unfilled slots charge nothing"); + assert_eq!(largest, 519, "and are not counted as asked for"); + } else { + // Thirteen slots at 65,535 groups: sixteen would be all of it. + assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most"); + assert_eq!(largest, u32::MAX); + } } - // SAFETY: a live buffer and an open list. - let gpu = unsafe { - list.list.ResourceBarrier(&[transition( - &buffer, + } + + #[test] + fn warp_budget_saturates_without_wraparound_and_preserves_draw_fields() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_INDEXED: u32 = 1; + const STRIDE: u32 = 24; // 5 indexed-draw words + 1 trailing custom word + const RECORDS: u32 = 128; // 2 waves of 64: old InterlockedAdd wrapped 2^32 at 64! + const BUDGET_CAP: u32 = 1 << 27; + + let total_bytes = (STRIDE * RECORDS) as usize; + let (src_buf, src_ptr, _) = warp.shared_buffer(total_bytes as u64); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(total_bytes as u64); + let dst_buf = warp.default_uav(total_bytes as u64); + + let mut initial_src = vec![0u8; total_bytes]; + for i in 0..RECORDS as usize { + let words: [u32; 6] = [ + u32::MAX, // IndexCount -> clamps to 1 << 24 + u32::MAX, // InstanceCount -> clamps to 4 (cost = 1 << 26) + 1000 + i as u32, // StartIndexLocation + (-200i32 + i as i32) as u32, // BaseVertexLocation + 5000 + i as u32, // StartInstanceLocation + 0xCAFE_0000 | (i as u32), // Extra stride word + ]; + let base = i * (STRIDE as usize); + for (w, val) in words.into_iter().enumerate() { + initial_src[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes()); + } + } + + // SAFETY: mapped buffers have sufficient capacity. + unsafe { + std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, total_bytes); + (budget_ptr as *mut u32).write_volatile(0); + std::ptr::write_bytes(readback_ptr, 0, total_bytes); + } + + assert!(record_clamp( + &warp.clamp, + &warp.list, + &dst_buf, + budget_gpu, + (&src_buf, 0), + None, + (KIND_INDEXED, STRIDE, RECORDS), + )); + done_on(&warp.list, &dst_buf); + + // SAFETY: open command list; copy clamped scratch buffer for verification. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list + .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total_bytes as u64); + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, )]); - buffer.GetGPUVirtualAddress() + } + warp.submit_and_wait(); + + // SAFETY: GPU work completed. + let (spent, after_src, out_words) = unsafe { + let spent = (budget_ptr as *const u32).read_volatile(); + let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), total_bytes).to_vec(); + let out_words = std::slice::from_raw_parts( + readback_ptr.cast::().cast_const(), + total_bytes / 4, + ) + .to_vec(); + (spent, after_src, out_words) }; - for (kind, at, stride) in [(0, 0, 16), (2, 16, 12), (3, 32, 12)] { - assert!(bound(&list, &buffer, gpu + at, (kind, stride, 1))); - done(&list, &buffer); + + assert_eq!( + spent, BUDGET_CAP, + "budget must saturate at BUDGET without wrapping" + ); + assert_eq!(after_src, initial_src, "src_args must remain untouched"); + + let mut kept = 0usize; + let mut zeroed = 0usize; + for i in 0..RECORDS as usize { + let rec = &out_words[i * 6..(i + 1) * 6]; + if rec[0] == (1 << 24) && rec[1] == 4 { + kept += 1; + } else { + assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed"); + zeroed += 1; + } + assert_eq!(rec[2], 1000 + i as u32); + assert_eq!(rec[3], (-200i32 + i as i32) as u32); + assert_eq!(rec[4], 5000 + i as u32); + assert_eq!(rec[5], 0xCAFE_0000 | (i as u32)); } + assert_eq!((kept, zeroed), (2, (RECORDS as usize) - 2)); + } + + /// Exercises `HostList::indirect_scratch`, `bound`, `done`, `Host::execute`, + /// and `HostList::reset` end-to-end on the host device. + #[test] + fn host_list_reuses_and_grows_scratch_across_submissions() { + let Some(host) = super::host() else { + return; + }; + let Ok(list) = host.new_list() else { + return; + }; + let Some((src_buf, src_ptr)) = host.shared_buffer(256 << 10) else { + return; + }; + let Some((count_buf, count_ptr)) = host.shared_buffer(256) else { + return; + }; + // SAFETY: mapped host buffers. + unsafe { + std::ptr::write_bytes(src_ptr, 0x7F, 256 << 10); + (count_ptr as *mut u32).write_volatile(2); + } + + // First two calls fit inside the initial 64 KiB scratch buffer and + // must reuse the exact same `ID3D12Resource`. + let b1 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (0, 16, 64)).unwrap(); + done(&list, &b1); + let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap(); + done(&list, &b2); + assert_eq!( + b1.as_raw(), + b2.as_raw(), + "scratch buffer within capacity must be reused" + ); + + // A call needing >64 KiB grows the scratch buffer mid-list while keeping + // `b1` alive until reset. + let b3 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 5000)).unwrap(); + done(&list, &b3); + assert_ne!( + b3.as_raw(), + b1.as_raw(), + "larger request must grow scratch buffer" + ); + + list.close(); + host.execute(&[&list]); + list.reset(); + + // After reset, requests up to the grown high-water mark reuse `b3` with + // zero new allocations. + let b4 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 4096)).unwrap(); + done(&list, &b4); + assert_eq!( + b4.as_raw(), + b3.as_raw(), + "grown scratch buffer must persist across reset" + ); list.close(); host.execute(&[&list]); - // SAFETY: the list ran (execute waits); inside the mapped bytes. - let read = |at: usize| unsafe { std::slice::from_raw_parts(words.add(at / 4), 3).to_vec() }; - assert_eq!(read(0)[..2], [1 << 24, 4]); - assert_eq!(read(16), [65_535, 2, 3]); - assert_eq!(read(32), [65_535, 1, 1]); + list.reset(); + } +} + +/// What one small draw costs this card, bare and with one thing changed +/// between every two draws: a measurement, not a check (it asserts only +/// that the card answered). The timing run of the lit scene (run 187) has +/// some 11,000 small commands a frame at 5 to 16 microseconds each, and no +/// log says whether that is what we put around a command or what the card +/// takes for one. Each variant here is 10,000 one-triangle draws into a +/// 2560x1440 target, timed on the card by one pair of timestamps around +/// the whole batch (not one per command, which would time the stamps). +/// +/// Run by name, no game needed: +/// `cargo test -p victory-gpu --release -- --ignored bare_command_cost --nocapture` +#[cfg(test)] +mod bare_cost { + use windows::Win32::Foundation::{HANDLE, RECT}; + use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY}; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::{Interface, s}; + + use crate::host::{compile, transition}; + + /// Draws in a batch. + const DRAWS: u32 = 10_000; + const WIDTH: u32 = 2560; + const HEIGHT: u32 = 1440; + + /// One small triangle in the middle of the target (about 180 pixels), + /// and two pixel programs that read one texel of a texture through a + /// table, so that the view heap set is in use. + const DRAW: &str = r#" +#define RS "DescriptorTable(SRV(t0))" +Texture2D image : register(t0); +[RootSignature(RS)] +float4 corner(uint i : SV_VertexID) : SV_Position { + float2 p = float2((i << 1) & 2, i & 2); + return float4(p * 0.02 - 0.01, 0.5, 1.0); +} +[RootSignature(RS)] +float4 first(float4 at : SV_Position) : SV_Target { + return image.Load(int3(0, 0, 0)); +} +[RootSignature(RS)] +float4 second(float4 at : SV_Position) : SV_Target { + return 1.0 - image.Load(int3(0, 0, 0)); +} +"#; + + /// A compute pass of next to nothing, as our clamp of an indirect + /// record is: one group of one thread that writes one word. + const WORK: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer words : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void work() { + words.Store(0, words.Load(0) + 1); +} +"#; + + /// What changes between every two draws of a batch. + #[derive(Clone, Copy, PartialEq)] + enum Between { + /// Nothing. + Nothing, + /// The pipeline: two alternate. + Pipeline, + /// A second texture goes from target to shader read and back. + BarrierPair, + /// The depth texture bound for testing goes from write to read or + /// back. + DepthMove, + /// The pair of descriptor heaps: two pairs alternate. + Heaps, + /// The colour target: two alternate. + Targets, + /// A compute pass of ours of one group, and the pipeline back. + Compute, + /// The same between two waits for every earlier shader write, as + /// the clamp records them. + ComputeWithWaits, + } + + struct Rig { + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + root: ID3D12RootSignature, + pipelines: [ID3D12PipelineState; 2], + work_root: ID3D12RootSignature, + work: ID3D12PipelineState, + words: ID3D12Resource, + other: ID3D12Resource, + depth: ID3D12Resource, + /// Kept alive: the views below name them. + _kept: Vec, + _target_heaps: [ID3D12DescriptorHeap; 2], + heap_pairs: [[Option; 2]; 2], + tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2], + targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2], + _depth_written: D3D12_CPU_DESCRIPTOR_HANDLE, + depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE, + stamps: ID3D12QueryHeap, + back: ID3D12Resource, + card: String, + } + + fn texture( + device: &ID3D12Device, + (width, height): (u32, u32), + format: DXGI_FORMAT, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(width), + Height: height, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: plain texture creation. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + fn buffer( + device: &ID3D12Device, + size: u64, + kind: D3D12_HEAP_TYPE, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: plain buffer creation. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + fn heap(device: &ID3D12Device, kind: D3D12_DESCRIPTOR_HEAP_TYPE, count: u32, visible: bool) -> ID3D12DescriptorHeap { + let flags = if visible { + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE + } else { + D3D12_DESCRIPTOR_HEAP_FLAG_NONE + }; + // SAFETY: plain heap creation. + unsafe { + device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: flags, + NodeMask: 0, + }) + .unwrap() + } + } + + fn pipeline(device: &ID3D12Device, root: &ID3D12RootSignature, vs: &[u8], ps: &[u8]) -> ID3D12PipelineState { + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = 0xf; + let mut formats = [DXGI_FORMAT(0); 8]; + formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + // SAFETY: the description points at live data and never releases + // its pointer to the root signature. + unsafe { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(root), + VS: code(vs), + PS: code(ps), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // Depth is tested and never written, so the texture may be + // in the write state or in the read state under one view. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: formats, + DSVFormat: DXGI_FORMAT_D32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + device.CreateGraphicsPipelineState(&desc).unwrap() + } + } + + impl Rig { + /// The default adapter, as the layer takes it; `None` without one + /// or on a software adapter. + fn new() -> Option { + let vs = compile(DRAW, s!("corner"), s!("vs_5_1")).ok()?; + let ps = [ + compile(DRAW, s!("first"), s!("ps_5_1")).ok()?, + compile(DRAW, s!("second"), s!("ps_5_1")).ok()?, + ]; + let cs = compile(WORK, s!("work"), s!("cs_5_1")).ok()?; + // SAFETY: plain object creation on a device of our own; the + // views are made in heaps that live as long as the rig. + unsafe { + let mut device: Option = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let desc = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid())) + .ok()? + .cast::() + .ok()? + .GetDesc1() + .ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + return None; + } + let card = String::from_utf16_lossy(&desc.Description) + .trim_end_matches('\0') + .to_owned(); + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = + device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs[..]).ok()?; + let pipelines = [ + pipeline(&device, &root, &vs, &ps[0]), + pipeline(&device, &root, &vs, &ps[1]), + ]; + let work_root: ID3D12RootSignature = device.CreateRootSignature(0, &cs[..]).ok()?; + let work: ID3D12PipelineState = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&work_root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }) + .ok()?; + + let size = (WIDTH, HEIGHT); + let colour = |state| texture(&device, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, state); + let target = [ + colour(D3D12_RESOURCE_STATE_RENDER_TARGET), + colour(D3D12_RESOURCE_STATE_RENDER_TARGET), + ]; + let other = colour(D3D12_RESOURCE_STATE_RENDER_TARGET); + let depth = texture( + &device, + size, + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + ); + let image = texture( + &device, + (4, 4), + DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + ); + let words = buffer( + &device, + 64 << 10, + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ); + let back = buffer( + &device, + 16, + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let mut stamps: Option = None; + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2, + NodeMask: 0, + }, + &mut stamps, + ) + .ok()?; + let stamps = stamps?; + + // Target and depth views. + let rtvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, false); + let rtv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let mut targets = [rtvs.GetCPUDescriptorHandleForHeapStart(); 2]; + targets[1].ptr += rtv_step; + device.CreateRenderTargetView(&target[0], None, targets[0]); + device.CreateRenderTargetView(&target[1], None, targets[1]); + let dsvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, false); + let dsv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let depth_written = dsvs.GetCPUDescriptorHandleForHeapStart(); + let mut depth_tested = depth_written; + depth_tested.ptr += dsv_step; + device.CreateDepthStencilView(&depth, None, depth_written); + let tested = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH, + ..Default::default() + }; + device.CreateDepthStencilView(&depth, Some(&tested), depth_tested); + + // Two pairs of shader-visible heaps: views (one view of the + // small texture each) and samplers (none used). + let view_heaps = [ + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), + ]; + let sampler_heaps = [ + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), + ]; + for views in &view_heaps { + device.CreateShaderResourceView(&image, None, views.GetCPUDescriptorHandleForHeapStart()); + } + let tables = [ + view_heaps[0].GetGPUDescriptorHandleForHeapStart(), + view_heaps[1].GetGPUDescriptorHandleForHeapStart(), + ]; + let heap_pairs = [ + [Some(view_heaps[0].clone()), Some(sampler_heaps[0].clone())], + [Some(view_heaps[1].clone()), Some(sampler_heaps[1].clone())], + ]; + + // The first list: both targets and the depth texture cleared. + list.ClearRenderTargetView(targets[0], &[0.0; 4], None); + list.ClearRenderTargetView(targets[1], &[0.0; 4], None); + list.ClearDepthStencilView(depth_written, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); + let [first_target, second_target] = target; + let mut rig = Rig { + queue, + allocator, + list, + fence, + submitted: 0, + event, + root, + pipelines, + work_root, + work, + words, + other, + depth, + _kept: vec![first_target, second_target, image], + _target_heaps: [rtvs, dsvs], + heap_pairs, + tables, + targets, + _depth_written: depth_written, + depth_tested, + stamps, + back, + card, + }; + rig.finish(); + Some(rig) + } + } + + /// Closes the open list, runs it, waits for the card and opens the + /// list again. + fn finish(&mut self) { + self.submitted += 1; + // SAFETY: our list, queue and fence; the allocator is reset + // only after the card finished everything recorded from it. + unsafe { + self.list.Close().unwrap(); + let run: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); + WaitForSingleObject(self.event, INFINITE); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + + /// What every list starts with: a new list has nothing set. + fn begin(&self) { + let l = &self.list; + // SAFETY: an open list and live objects and views. + unsafe { + l.SetDescriptorHeaps(&self.heap_pairs[0]); + l.SetGraphicsRootSignature(&self.root); + l.SetPipelineState(&self.pipelines[0]); + l.SetGraphicsRootDescriptorTable(0, self.tables[0]); + l.OMSetRenderTargets(1, Some(&self.targets[0]), false, Some(&self.depth_tested)); + l.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: WIDTH as f32, + Height: HEIGHT as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + l.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: WIDTH as i32, + bottom: HEIGHT as i32, + }]); + // A triangle list. + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4)); + } + } + + /// One batch of [`DRAWS`] draws in `lists` lists run one by one, + /// with `between` recorded before every draw: the microseconds a + /// draw took on the card, and the milliseconds recording took. + fn batch(&mut self, between: Between, lists: u32) -> (f64, f64) { + let (target, read, written, tested) = ( + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_DEPTH_READ, + ); + let started = std::time::Instant::now(); + let mut drawn = 0u32; + for part in 0..lists { + let l = &self.list; + // SAFETY: an open list; our query heap; live objects. + unsafe { + if part == 0 { + l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + } + } + self.begin(); + // SAFETY: an open list with everything set; live objects. + // Every state moved is moved back within the batch (the + // draws of a list are an even number). + unsafe { + for _ in 0..DRAWS / lists { + let odd = (drawn % 2) as usize; + match between { + Between::Nothing => {} + Between::Pipeline => l.SetPipelineState(&self.pipelines[odd]), + Between::BarrierPair => { + l.ResourceBarrier(&[transition(&self.other, target, read)]); + l.ResourceBarrier(&[transition(&self.other, read, target)]); + } + Between::DepthMove => { + let (from, to) = if odd == 0 { (written, tested) } else { (tested, written) }; + l.ResourceBarrier(&[transition(&self.depth, from, to)]); + } + Between::Heaps => { + l.SetDescriptorHeaps(&self.heap_pairs[odd]); + l.SetGraphicsRootDescriptorTable(0, self.tables[odd]); + } + Between::Targets => { + l.OMSetRenderTargets(1, Some(&self.targets[odd]), false, Some(&self.depth_tested)); + } + Between::Compute | Between::ComputeWithWaits => { + let waits = between == Between::ComputeWithWaits; + if waits { + l.ResourceBarrier(&[super::uav_barrier()]); + } + l.SetComputeRootSignature(&self.work_root); + l.SetPipelineState(&self.work); + l.SetComputeRootUnorderedAccessView(0, self.words.GetGPUVirtualAddress()); + l.Dispatch(1, 1, 1); + if waits { + l.ResourceBarrier(&[super::uav_barrier()]); + } + l.SetPipelineState(&self.pipelines[0]); + } + } + l.DrawInstanced(3, 1, 0, 0); + drawn += 1; + } + if part + 1 < lists { + // The next list of the batch: this one is sent on + // its own and the list is opened again at once + // (the allocator is not reset before the card is + // done with all of them). + l.Close().unwrap(); + let run: ID3D12CommandList = l.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + l.Reset(&self.allocator, None).unwrap(); + } else { + l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + l.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0); + } + } + } + let recording = started.elapsed().as_secs_f64() * 1e3; + self.finish(); + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: 16 }; + // SAFETY: a read-back buffer the finished list resolved two + // timestamps into. + let ticks = unsafe { + self.back.Map(0, Some(&range), Some(&mut data)).unwrap(); + let stamps = std::slice::from_raw_parts(data.cast::(), 2).to_vec(); + self.back.Unmap(0, None); + stamps[1].saturating_sub(stamps[0]) + }; + // SAFETY: a plain query of our queue. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1).max(1); + (ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), recording) + } + } + + #[test] + #[ignore = "a measurement on the card: run it by name with --ignored --nocapture"] + fn bare_command_cost() { + let Some(mut rig) = Rig::new() else { + eprintln!("no hardware adapter, or our shaders did not compile; skipped"); + return; + }; + eprintln!("bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", rig.card); + // The first batch pays for whatever the driver does at first use. + rig.batch(Between::Nothing, 1); + let variants = [ + ("(a) nothing changes between draws", Between::Nothing, 1), + ("(b) another pipeline every draw", Between::Pipeline, 1), + ("(c) a barrier pair on a second texture every draw", Between::BarrierPair, 1), + ("(d) the tested depth texture moved between write and read every draw", Between::DepthMove, 1), + ("(e) another pair of descriptor heaps every draw", Between::Heaps, 1), + ("(f) another colour target every draw", Between::Targets, 1), + ("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100), + ("(h) a compute pass of ours of one group before every draw", Between::Compute, 1), + ("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1), + ]; + let mut least = Vec::new(); + for (name, between, lists) in variants { + let mut runs: Vec<(f64, f64)> = (0..3).map(|_| rig.batch(between, lists)).collect(); + runs.sort_by(|a, b| a.0.total_cmp(&b.0)); + eprintln!( + "{name}: {:.2} microseconds a draw on the card (the three: {:.2}, {:.2}, {:.2}); recording took {:.1} ms", + runs[0].0, runs[0].0, runs[1].0, runs[2].0, runs[0].1 + ); + least.push(runs[0].0); + } + assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch"); } } diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs new file mode 100644 index 0000000..25461df --- /dev/null +++ b/crates/victory-gpu/src/inplace.rs @@ -0,0 +1,1170 @@ +//! Title memory as the card's own memory: a host heap opened on memory +//! the title already has, and a buffer placed in it, so that shaders read +//! and write the title's bytes themselves and no host copy stands between +//! (the console's one memory). This file holds the two openings Direct3D +//! has, a probe that says what this PC's driver makes of them +//! (`VICTORY_INPLACE_PROBE`), and a census of which title memory could be +//! opened. +//! +//! What the Direct3D runtime and the kernel answer, measured on this PC +//! with the software adapter (the rules are theirs, not the adapter's; +//! what the card's driver adds is what the probe is for): +//! +//! - `OpenExistingHeapFromAddress` takes the base address of a whole +//! `VirtualAlloc` allocation and nothing inside it; every page must be +//! committed and have one protection. Opening locks every page into the +//! PC's memory at once (256 MiB never touched: 70 ms and 256 MB of +//! working set). +//! - `OpenExistingHeapFromAddress1` (`ID3D12Device13`) takes any committed +//! part of an allocation, with the same rule for its pages; parts may +//! overlap, and the whole may be opened beside them. It also takes a +//! committed view of a section. +//! - `OpenExistingHeapFromFileMapping` takes a section made with +//! `SEC_COMMIT` and refuses one made with `SEC_RESERVE` (how `xmem` +//! makes the title's page pool today). The heap is the section, not a +//! view of it: views may be unmapped, mapped elsewhere or made +//! read-only, and the section's handle closed, with the heap alive. +//! Opening it locks nothing (256 MiB: 0.2 ms, no working set). +//! - The heap is a custom heap in the PC's memory (write-back pages, pool +//! L0), shared and cross-adapter shared, 64 KiB aligned. A buffer in it +//! must have `ALLOW_CROSS_ADAPTER`; unordered access beside it is taken. +//! A texture must be row-major with one level. Tile mappings into such +//! a heap are refused and REMOVE THE DEVICE: never call them. +//! - While a heap opened from an address stands, the title cannot +//! decommit, release or protect the pages in it (`VirtualFree` and +//! `VirtualProtect` fail with error 87), nor unmap a view in it. Pages +//! outside the opened part are free to change. + +use std::collections::BTreeMap; +use std::ffi::c_void; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; +use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; +use windows::core::{Interface, s}; +use windows_sys::Win32::System::Memory as mem; + +/// The unit heaps and placed buffers are cut on, and the console's page. +const K64: usize = 64 << 10; +/// The host's write watching (not in windows-sys' memory module). +const MEM_WRITE_WATCH: u32 = 0x20_0000; + +/// `VICTORY_INPLACE_PROBE`: 0 (unset) nothing; 1 the probe on memory of +/// its own at the first sweep, and the census 30 and 150 seconds later; +/// 2 also opens one part of the title's own memory for a moment at the +/// first census. +pub(crate) fn probe_level() -> u8 { + static LEVEL: std::sync::OnceLock = std::sync::OnceLock::new(); + *LEVEL.get_or_init(|| std::env::var("VICTORY_INPLACE_PROBE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// `VICTORY_INPLACE`: 0 (unset) off. 1: a window of title memory outside +/// buffers that lies in private memory committed whole is not copied: a +/// part of the title's allocation is opened as a host heap and the window +/// is a buffer placed over it ([`place_for`]). 2: title buffers too, +/// except the big ones in the card's memory. +/// +/// What stage 1 covers is private memory (`XMemVirtualAlloc`'s). View +/// memory (the page pool) is turned down here: its section is made +/// reserved, which the host refuses, and what a view shows changes when +/// the title maps pages. +/// +/// What it assumes, for 2: nothing reads title memory that a submission +/// not yet run writes through such a buffer. With every submission waited +/// for (the default) that holds; with `VICTORY_LATE_WAIT` it does not, +/// since the flights' rules know shader writes only by the ranges copies +/// declare. Do not combine 2 with late wait. +/// +/// shortcut: while a window is in place the title cannot decommit, free +/// or protect its pages (the call fails with error 87; the probe shows +/// it). The title's heaps are allocated once and kept, and nothing of the +/// kind was seen; [`title_memory_freeing`] is there for the runtime to +/// call before such a call once it takes them over. +pub(crate) fn level() -> u8 { + static LEVEL: std::sync::OnceLock = std::sync::OnceLock::new(); + *LEVEL.get_or_init(|| std::env::var("VICTORY_INPLACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// The most title memory in place at once, in bytes +/// (`VICTORY_INPLACE_MB`, 4096): opening locks the pages into the PC's +/// memory, also those the title never touched. +fn most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| std::env::var("VICTORY_INPLACE_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(4096) << 20) +} + +/// In place now: windows and their bytes, title buffers and their bytes; +/// then, since the start: asks turned down because the memory is a view +/// or not private memory committed whole, because the host refused, +/// because of [`most`]; and what was let go because its memory changed. +static STATS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + +/// A buffer placed over title memory, and its heap. +pub(crate) struct Placed { + pub(crate) buffer: ID3D12Resource, + pub(crate) heap: ID3D12Heap, + /// The host GPU address of the title memory's first byte. + pub(crate) gpu: u64, + /// Bytes from the buffer's first byte to the title memory's first. + pub(crate) bias: u64, +} + +/// Opens the 64 KiB pages that hold title memory `[start, start + len)` +/// as a heap of their own and places one buffer over all of them. `Err` +/// with nothing if the memory is not private memory committed whole +/// (nothing was asked of the host), with the host's error if it refused. +pub(crate) fn place_part(device: &ID3D12Device, start: u64, len: u64) -> Result> { + let at = start & !(K64 as u64 - 1); + let bytes = (start + len.max(1)).next_multiple_of(K64 as u64) - at; + if !private_whole(at as usize, bytes as usize) { + return Err(None); + } + let heap = open(device, From::Part(at as usize, bytes as usize)).map_err(Some)?; + let buffer = place(device, &heap, 0, bytes).map_err(Some)?; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() } + (start - at); + Ok(Placed { buffer, heap, gpu, bias: start - at }) +} + +/// Title memory `[start, start + len)` in place, for a window outside +/// buffers or a title buffer, if [`level`] asks for it and the memory can +/// be opened; `None` leaves the caller to make a copy, as before. +pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option { + if level() < if window { 1 } else { 2 } { + return None; + } + // View memory: known from the runtime without asking Windows. + if cover(start as usize, len as usize) != Cover::None { + STATS[4].fetch_add(1, Ordering::Relaxed); + return None; + } + if STATS[1].load(Ordering::Relaxed) + STATS[3].load(Ordering::Relaxed) + len > most() { + STATS[6].fetch_add(1, Ordering::Relaxed); + return None; + } + let host = crate::host::host()?; + match place_part(&host.device, start, len) { + Ok(placed) => { + let at = if window { 0 } else { 2 }; + STATS[at].fetch_add(1, Ordering::Relaxed); + STATS[at + 1].fetch_add(len, Ordering::Relaxed); + Some(placed) + } + Err(None) => { + STATS[4].fetch_add(1, Ordering::Relaxed); + None + } + Err(Some(e)) => { + if STATS[5].fetch_add(1, Ordering::Relaxed) < 8 { + tracing::warn!(start = format_args!("{start:#x}"), len, error = %e, "title memory not opened in place: a copy instead"); + } + None + } + } +} + +/// What [`place_for`] gave is gone. +pub(crate) fn gone(window: bool, bytes: u64) { + let at = if window { 0 } else { 2 }; + STATS[at].fetch_sub(1, Ordering::Relaxed); + STATS[at + 1].fetch_sub(bytes, Ordering::Relaxed); +} + +/// Title memory `[at, at + len)` is about to show something else, or the +/// title is about to decommit, free or protect it: what is in place there +/// is let go (the tables forget it; its heap goes when the last list and +/// slot that hold it do). Called for memory the runtime maps anew; for +/// the runtime to call before the title's own `VirtualFree` once it takes +/// that call over. +pub fn title_memory_freeing(at: usize, len: usize) { + if STATS[0].load(Ordering::Relaxed) + STATS[2].load(Ordering::Relaxed) == 0 { + return; + } + let gone = crate::shadow::in_place_let_go(at as u64, len as u64); + STATS[7].fetch_add(gone, Ordering::Relaxed); +} + +/// The line of what is in place, every ten seconds while [`level`] is on. +fn say() { + static LAST: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms(); + let last = LAST.load(Ordering::Relaxed); + if now < last + 10_000 || LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + tracing::info!( + "title memory in place: {} windows {} MB, {} title buffers {} MB (no copy, no refresh, no copy-back); turned down: {} view memory or not private memory committed whole, \ + {} refused by the host, {} over VICTORY_INPLACE_MB; {} let go because their memory changed", + s[0], + s[1] >> 20, + s[2], + s[3] >> 20, + s[4], + s[5], + s[6], + s[7] + ); +} + +/// What a heap is opened on. +pub(crate) enum From { + /// A whole `VirtualAlloc` allocation, by its base address. + Region(usize), + /// A committed part of one: address and bytes. + Part(usize, usize), + /// A section made with `SEC_COMMIT`, by its handle. + Section(usize), +} + +/// Opens a heap on memory the process has. +pub(crate) fn open(device: &ID3D12Device, from: From) -> windows::core::Result { + // SAFETY: the calls take an address or a handle and check both + // themselves; a refusal is an error code. + unsafe { + match from { + From::Region(at) => device.cast::()?.OpenExistingHeapFromAddress(at as *const c_void), + From::Part(at, bytes) => device.cast::()?.OpenExistingHeapFromAddress1(at as *const c_void, bytes), + From::Section(handle) => device.cast::()?.OpenExistingHeapFromFileMapping(HANDLE(handle as *mut c_void)), + } + } +} + +fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + } +} + +/// A buffer of `size` bytes at `offset` (a multiple of 64 KiB) of an +/// opened heap, which shaders may read and write, in the common state. +pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: u64) -> windows::core::Result { + let mut placed: Option = None; + // The heap is cross-adapter shared, so the buffer must say so too. + let flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + // SAFETY: plain creation in a live heap. + unsafe { device.CreatePlacedResource(heap, offset, &buffer_desc(size, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut placed)? }; + placed.ok_or_else(windows::core::Error::empty) +} + +// The title's views of its physical pages, as the runtime maps them: the +// census needs them to say which view memory is one run of a section (one +// placed buffer could show it) and which is scattered pages. + +struct Views { + /// By address: bytes, the section's handle, the offset in it. + views: BTreeMap, + /// Sections by handle: bytes, and whether made committed. + sections: Vec<(usize, u64, bool)>, +} + +static VIEWS: Mutex = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new() }); + +fn views() -> std::sync::MutexGuard<'static, Views> { + VIEWS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The runtime made a section of `bytes` for physical pages; `committed` +/// if with `SEC_COMMIT` (only such a section can be opened as a heap). +pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { + let mut v = views(); + v.sections.retain(|s| s.0 != section); + v.sections.push((section, bytes, committed)); +} + +/// The runtime mapped `[at, at + len)` as a view of `section` from +/// `offset` on. Call after [`crate::title_memory_remapped`] of the range. +pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { + views().views.insert(at, (len, section, offset)); +} + +/// What `[at, at + len)` showed is gone ([`crate::title_memory_remapped`]): +/// the views that touch it are forgotten (the runtime tells again those it +/// maps anew). +pub(crate) fn views_gone(at: usize, len: usize) { + let mut v = views(); + if v.views.is_empty() { + return; + } + let end = at.saturating_add(len); + let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base); + let gone: Vec = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect(); + for base in gone { + v.views.remove(&base); + } +} + +/// How the views cover `[at, at + len)`. +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub(crate) enum Cover { + /// No view holds its first byte. + None, + /// Views hold a part of it only. + Holes, + /// Views hold all of it, from more than one place. + Scattered, + /// All of it is one run of one section: the section and the offset of + /// `at` in it. + Run(usize, u64), +} + +fn cover_in(views: &BTreeMap, at: usize, len: usize) -> Cover { + let end = at + len.max(1); + let Some((&base, &(bytes, section, offset))) = views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at) else { + return Cover::None; + }; + let first = (section, offset + (at - base) as u64); + let (mut reached, mut one) = (base + bytes, true); + while reached < end { + let Some(&(bytes, s, o)) = views.get(&reached) else { + return Cover::Holes; + }; + one &= s == first.0 && o == first.1 + (reached - at) as u64; + reached += bytes; + } + if one { Cover::Run(first.0, first.1) } else { Cover::Scattered } +} + +/// [`Cover`] of `[at, at + len)` by the title's views as they are now. +pub(crate) fn cover(at: usize, len: usize) -> Cover { + cover_in(&views().views, at, len) +} + +/// Whether `[at, at + len)` is private memory, all committed and +/// read-write: what [`From::Part`] takes. One question to Windows (it +/// walks the page tables to the end of the pages that share the first +/// one's state: a millisecond in the title's big blocks, so ask when a +/// copy is made, not when it is used). +pub(crate) fn private_whole(at: usize, len: usize) -> bool { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + n != 0 + && info.State == mem::MEM_COMMIT + && info.Type == mem::MEM_PRIVATE + && info.Protect == mem::PAGE_READWRITE + && (info.BaseAddress as usize).saturating_add(info.RegionSize) >= at.saturating_add(len) +} + +fn hr(result: &windows::core::Result) -> String { + match result { + Ok(_) => "ok".to_owned(), + Err(e) => format!("REFUSED {:#010x} ({})", e.code().0, e.message().trim()), + } +} + +/// A queue, a list and a fence of the probe's own on `device`: nothing of +/// the host's submissions is touched. +struct Rig { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + done: u64, + event: HANDLE, +} + +impl Drop for Rig { + fn drop(&mut self) { + // SAFETY: our event. + unsafe { + let _ = windows::Win32::Foundation::CloseHandle(self.event); + } + } +} + +impl Rig { + fn new(device: &ID3D12Device) -> windows::core::Result { + // SAFETY: plain creation of objects of our own. + unsafe { + let queue: ID3D12CommandQueue = + device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })?; + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.Close()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + Ok(Rig { device: device.clone(), queue, allocator, list, fence, done: 0, event }) + } + } + + /// Records with `record`, runs it and waits (ten seconds at most). + fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> windows::core::Result<()> { + // SAFETY: our own list and queue, one run at a time. + unsafe { + self.allocator.Reset()?; + self.list.Reset(&self.allocator, None)?; + record(&self.list); + self.list.Close()?; + self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]); + self.done += 1; + self.queue.Signal(&self.fence, self.done)?; + self.fence.SetEventOnCompletion(self.done, self.event)?; + if WaitForSingleObject(self.event, 10_000).0 != 0 { + return Err(windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)); + } + self.device.GetDeviceRemovedReason() + } + } + + fn committed(&self, kind: D3D12_HEAP_TYPE, size: u64, state: D3D12_RESOURCE_STATES) -> windows::core::Result { + let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + let mut buffer: Option = None; + // SAFETY: plain creation. + unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, D3D12_RESOURCE_FLAG_NONE), state, None, &mut buffer)? + }; + buffer.ok_or_else(windows::core::Error::empty) + } + + /// What the GPU reads of `size` bytes of `resource` from `offset`. + fn fetch(&mut self, resource: &ID3D12Resource, offset: u64, size: usize) -> windows::core::Result> { + let back = self.committed(D3D12_HEAP_TYPE_READBACK, size as u64, D3D12_RESOURCE_STATE_COPY_DEST)?; + // SAFETY: two live buffers, the range inside both. + self.run(|list| unsafe { list.CopyBufferRegion(&back, 0, resource, offset, size as u64) })?; + let mut data = std::ptr::null_mut(); + // SAFETY: the mapping holds `size` bytes until unmapped. + unsafe { + back.Map(0, None, Some(&mut data))?; + let bytes = std::slice::from_raw_parts(data.cast::(), size).to_vec(); + back.Unmap(0, None); + Ok(bytes) + } + } + + /// The GPU writes `bytes` at `offset` of `resource` (a copy). + fn store(&mut self, resource: &ID3D12Resource, offset: u64, bytes: &[u8]) -> windows::core::Result<()> { + let up = self.committed(D3D12_HEAP_TYPE_UPLOAD, bytes.len() as u64, D3D12_RESOURCE_STATE_GENERIC_READ)?; + let mut data = std::ptr::null_mut(); + // SAFETY: the mapping holds the buffer's bytes until unmapped. + unsafe { + up.Map(0, None, Some(&mut data))?; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.cast::(), bytes.len()); + up.Unmap(0, None); + } + // SAFETY: two live buffers, the range inside both. + self.run(|list| unsafe { list.CopyBufferRegion(resource, offset, &up, 0, bytes.len() as u64) }) + } + + /// A compute shader stores, through a root unordered-access view at + /// `gpu`, the sum of the buffer's first two words in its third. + fn shade(&mut self, gpu: u64) -> windows::core::Result<()> { + const SOURCE: &str = "#define RS \"UAV(u0)\"\nRWByteAddressBuffer b : register(u0);\n[RootSignature(RS)]\n[numthreads(1, 1, 1)]\nvoid main() { b.Store(8, b.Load(0) + b.Load(4)); }\n"; + let mut code: Option = None; + // SAFETY: the source and names live through the call; then the + // blob's own bytes, which hold the root signature too. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("inplace"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?; + let code = code.ok_or_else(windows::core::Error::empty)?; + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, + ..Default::default() + })?; + (root, pso) + }; + // SAFETY: an open list of ours; the view names a live buffer. + self.run(|list| unsafe { + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, gpu); + list.Dispatch(1, 1, 1); + }) + } + + /// Milliseconds the card takes to copy `bytes` of `from` into its own + /// memory, the best of three. + fn copy_ms(&mut self, from: &ID3D12Resource, bytes: u64) -> windows::core::Result { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut to: Option = None; + // SAFETY: plain creation. + unsafe { + self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, None, &mut to)? + }; + let to = to.ok_or_else(windows::core::Error::empty)?; + let mut best = f64::MAX; + for _ in 0..3 { + let started = std::time::Instant::now(); + // SAFETY: two live buffers of `bytes` bytes or more. + self.run(|list| unsafe { list.CopyBufferRegion(&to, 0, from, 0, bytes) })?; + best = best.min(started.elapsed().as_secs_f64() * 1000.0); + } + Ok(best) + } +} + +fn fill(at: *mut u8, len: usize, seed: u8) { + for i in 0..len { + // SAFETY: the caller's own committed memory of `len` bytes. + unsafe { at.add(i).write((i as u8).wrapping_mul(31).wrapping_add(seed)) }; + } +} + +fn same(at: *const u8, bytes: &[u8]) -> bool { + // SAFETY: the caller's own committed memory of that length. + unsafe { std::slice::from_raw_parts(at, bytes.len()) == bytes } +} + +/// The process's working set in MB. +fn working_set_mb() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + let mut counters = PROCESS_MEMORY_COUNTERS { cb: size_of::() as u32, ..Default::default() }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut counters, counters.cb) }; + counters.WorkingSetSize as u64 >> 20 +} + +/// What the probe found. The lines are the whole account; the flags are +/// what the stages build on. +#[derive(Default)] +pub(crate) struct Probe { + pub(crate) lines: Vec, + /// A part of private, write-watched memory opens, a buffer in it shows + /// the memory's bytes to the GPU, also those the CPU wrote afterwards. + pub(crate) part_reads: bool, + /// What the GPU writes there (a copy, and a shader through unordered + /// access) the CPU reads at the memory's address. + pub(crate) part_writes: bool, + /// The same two for a committed section, through a view of it. + pub(crate) section_reads: bool, + pub(crate) section_writes: bool, + /// The section's heap outlives the view: the GPU's write with no view + /// mapped shows in a view mapped afterwards. + pub(crate) section_outlives_views: bool, + /// A section made with `SEC_RESERVE` (as `xmem` makes the page pool) + /// was refused. + pub(crate) reserved_section_refused: bool, +} + +/// Tries the openings on memory of the probe's own, made the way `xmem` +/// makes title memory, with a queue of its own on `device`; `memory` +/// gives the card's memory account (`Host::video_memory`) where there is +/// one. Nothing of the title's is touched. `mb` is the size of the cost +/// measurement (0 leaves it out). +pub(crate) fn probe(device: &ID3D12Device, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) -> Probe { + let mut p = Probe::default(); + let mut rig = match Rig::new(device) { + Ok(rig) => rig, + Err(e) => { + p.lines.push(format!("no queue of its own: {e}")); + return p; + } + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + // SAFETY: a plain query that fills our structure. + let _ = unsafe { device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, (&raw mut options).cast(), size_of_val(&options) as u32) }; + p.lines.push(format!( + "the device: ID3D12Device3 {}, ID3D12Device13 {} (parts of an allocation); cross-adapter row-major textures {}; heap tier {}", + device.cast::().is_ok(), + device.cast::().is_ok(), + options.CrossAdapterRowMajorTextureSupported.as_bool(), + options.ResourceHeapTier.0 + )); + // SAFETY: memory of the probe's own, made and released here; every + // address used lies inside it. + unsafe { + private(&mut p, &mut rig); + section(&mut p, &mut rig); + if mb > 0 { + cost(&mut p, &mut rig, memory, mb); + } + } + p.lines.push(format!( + "VERDICT: private memory in place: reads {}, writes {}; the page pool's section in place: reads {}, writes {}, whatever the views do {}; \ + a reserved section is refused {} (the pool must be made committed to be opened)", + p.part_reads, p.part_writes, p.section_reads, p.section_writes, p.section_outlives_views, p.reserved_section_refused + )); + p +} + +fn describe(heap: &ID3D12Heap) -> String { + // SAFETY: a plain query. + let d = unsafe { heap.GetDesc() }; + format!( + "heap of {} KiB: type {} (4 = custom), CPU pages {} (3 = write-back), pool {} (1 = the PC's memory), alignment {}, flags {:#x} (0x1 shared, 0x20 cross-adapter, 0x200 write watch, 0x400 shader atomics)", + d.SizeInBytes >> 10, + d.Properties.Type.0, + d.Properties.CPUPageProperty.0, + d.Properties.MemoryPoolPreference.0, + d.Alignment, + d.Flags.0 + ) +} + +/// Private memory, reserved as `xmem` reserves the title's heaps +/// (committed, read-write, write-watched): a part of it opened. +unsafe fn private(p: &mut Probe, rig: &mut Rig) { + const SIZE: usize = 64 * K64; + // SAFETY (the whole function): the allocation below, `SIZE` bytes. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::(); + if base.is_null() { + p.lines.push("private memory: none to try with".to_owned()); + return; + } + // The part: 16 pages from the 16th on. + let (at, bytes) = (base.add(16 * K64), 16 * K64); + let whole = open(&rig.device, From::Region(base as usize)); + p.lines.push(format!("private memory, the whole allocation (OpenExistingHeapFromAddress): {}", hr(&whole))); + drop(whole); + let opened = open(&rig.device, From::Part(at as usize, bytes)); + p.lines.push(format!("private memory, a part of it (OpenExistingHeapFromAddress1): {}", hr(&opened))); + if let Ok(heap) = &opened { + p.lines.push(format!(" {}", describe(heap))); + let placed = place(&rig.device, heap, K64 as u64, 4 * K64 as u64); + p.lines.push(format!(" a buffer placed in it (cross-adapter, unordered access): {}", hr(&placed))); + if let Ok(buffer) = &placed { + let memory = at.add(K64); + fill(memory, 4 * K64, 1); + let first = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); + fill(memory, 4 * K64, 77); + let second = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); + p.part_reads = first && second; + p.lines.push(format!(" the GPU reads the memory's bytes: {first}; and those the CPU wrote afterwards, with no call in between: {second}")); + mem::ResetWriteWatch(base.cast(), SIZE); + let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x5a).collect(); + let copied = rig.store(buffer, 4096, &new).is_ok() && same(memory.add(4096), &new); + let (mut found, mut count, mut granularity) = ([0usize; 64], 64usize, 0u32); + let watched = mem::GetWriteWatch(0, base.cast(), SIZE, found.as_mut_ptr().cast(), &mut count, &mut granularity) == 0; + memory.cast::<[u32; 3]>().write([40, 2, 0]); + let shaded = rig.shade(buffer.GetGPUVirtualAddress()); + let shader = shaded.is_ok() && memory.cast::<[u32; 3]>().read()[2] == 42; + p.part_writes = copied && shader; + p.lines.push(format!( + " the CPU reads at the memory's address what the GPU wrote: by a copy {copied}; by a shader through unordered access {shader} ({}); \ + write watching saw {} of the copy's 16 pages{}", + hr(&shaded), + if watched { count } else { 0 }, + if watched { "" } else { " (the asking failed)" } + )); + } + // What the title can still do with the pages while the heap stands. + let mut old = 0; + let protect_in = mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READONLY, &mut old) != 0; + if protect_in { + mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READWRITE, &mut old); + } + let decommit_in = mem::VirtualFree(at.add(9 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + let decommit_out = mem::VirtualFree(base.add(40 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + p.lines.push(format!( + " with the heap standing, the title's own calls: read-only inside the part {protect_in}, decommit inside {decommit_in}, decommit outside {decommit_out} \ + (false inside means the heap must go before the title frees or guards those pages)" + )); + drop(placed); + } + drop(opened); + let freed = mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE) != 0; + p.lines.push(format!(" released after the heap went: {freed}")); + } +} + +/// A section and a view of it in a placeholder, as `xmem` maps physical +/// pages: reserved (as it is made today) and committed. +unsafe fn section(p: &mut Probe, rig: &mut Rig) { + const SIZE: usize = 32 * K64; + // SAFETY (the whole function): the sections, placeholder and views + // made below. + unsafe { + let process = windows_sys::Win32::System::Threading::GetCurrentProcess(); + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let reserved = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_RESERVE, 0, SIZE as u32, std::ptr::null()); + if !reserved.is_null() { + let opened = open(&rig.device, From::Section(reserved as usize)); + p.reserved_section_refused = opened.is_err(); + p.lines.push(format!("a section made reserved, as the page pool is today (OpenExistingHeapFromFileMapping): {}", hr(&opened))); + drop(opened); + windows_sys::Win32::Foundation::CloseHandle(reserved); + } + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null()); + let hole = mem::VirtualAlloc2(process, std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_RESERVE_PLACEHOLDER, mem::PAGE_NOACCESS, std::ptr::null_mut(), 0).cast::(); + if handle.is_null() || hole.is_null() { + p.lines.push("a committed section: none to try with".to_owned()); + return; + } + // Pages 4..12 of the section at the placeholder's start. + mem::VirtualFree(hole.cast(), 8 * K64, mem::MEM_RELEASE | mem::MEM_PRESERVE_PLACEHOLDER); + let view = mem::MapViewOfFile3(handle, process, hole.cast(), (4 * K64) as u64, 8 * K64, mem::MEM_REPLACE_PLACEHOLDER, mem::PAGE_READWRITE, std::ptr::null_mut(), 0); + let opened = open(&rig.device, From::Section(handle as usize)); + p.lines.push(format!("a section made committed (OpenExistingHeapFromFileMapping): {}", hr(&opened))); + let mut unmapped = false; + if let (Ok(heap), false) = (&opened, view.Value.is_null()) { + p.lines.push(format!(" {}", describe(heap))); + // The section's page 5 is the view's second page. + let placed = place(&rig.device, heap, 5 * K64 as u64, 2 * K64 as u64); + p.lines.push(format!(" a buffer placed at the section's offset of a view's pages: {}", hr(&placed))); + if let Ok(buffer) = &placed { + let memory = hole.add(K64); + fill(memory, 2 * K64, 3); + p.section_reads = rig.fetch(buffer, 0, 2 * K64).is_ok_and(|got| same(memory, &got)); + let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x33).collect(); + p.section_writes = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); + // The guard of `watch.rs`: the view read-only. + let mut old = 0; + let guarded = mem::VirtualProtect(memory.cast(), K64, mem::PAGE_READONLY, &mut old) != 0; + let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x44).collect(); + let through = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); + // The view goes; the GPU writes; another view shows it. + unmapped = mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER) != 0; + let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x55).collect(); + let stored = rig.store(buffer, 0, &new).is_ok(); + let other = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, (5 * K64) as u32, K64); + p.section_outlives_views = unmapped && stored && !other.Value.is_null() && same(other.Value.cast(), &new); + p.lines.push(format!( + " the GPU reads the view's bytes {}; the CPU reads through the view what the GPU wrote {}; the view made read-only under the heap {guarded}, \ + and the GPU writes it all the same {through}; the view unmapped under the heap {unmapped}, the GPU's write then shows in a view mapped afterwards {}", + p.section_reads, p.section_writes, p.section_outlives_views + )); + if !other.Value.is_null() { + mem::UnmapViewOfFile(other); + } + } + } + drop(opened); + if !unmapped && !view.Value.is_null() { + mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER); + } + windows_sys::Win32::Foundation::CloseHandle(handle); + // The placeholder was split in two: each half is released. + mem::VirtualFree(hole.cast(), 0, mem::MEM_RELEASE); + mem::VirtualFree(hole.add(8 * K64).cast(), 0, mem::MEM_RELEASE); + } +} + +/// What opening costs, on `mb` MB each of private memory never touched +/// and of a committed section never touched: the time, the working set, +/// the card's account of the PC's memory shared with it; and how fast the +/// card copies out of such a heap against a shared buffer of today's kind. +unsafe fn cost(p: &mut Probe, rig: &mut Rig, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) { + let bytes = mb << 20; + let shared = || memory().map_or(0, |m| m[3] >> 20); + let ms = |speed: Option| speed.map_or("?".to_owned(), |ms| format!("{ms:.1}")); + // SAFETY (the whole function): the allocation and the section below. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), bytes, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::(); + if !base.is_null() { + let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); + let opened = open(&rig.device, From::Part(base as usize, bytes)); + let took = started.elapsed().as_secs_f64() * 1000.0; + let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); + let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); + p.lines.push(format!( + "cost, {mb} MB of private memory never touched: {}; opened in {took:.1} ms; working set {set} -> {} MB; shared with the card {account} -> {} MB; \ + the card copies it out in {} ms", + hr(&opened), + working_set_mb(), + shared(), + ms(speed) + )); + drop((placed, opened)); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, (bytes as u64 >> 32) as u32, bytes as u32, std::ptr::null()); + if !handle.is_null() { + let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); + let opened = open(&rig.device, From::Section(handle as usize)); + let took = started.elapsed().as_secs_f64() * 1000.0; + let (set_opened, account_opened) = (working_set_mb(), shared()); + let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); + let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); + p.lines.push(format!( + "cost, {mb} MB of a committed section never touched: {}; opened in {took:.1} ms; working set {set} -> {set_opened} -> after the card read all of it {} MB; \ + shared with the card {account} -> {account_opened} -> {} MB; the card copies it out in {} ms", + hr(&opened), + working_set_mb(), + shared(), + ms(speed) + )); + drop((placed, opened)); + windows_sys::Win32::Foundation::CloseHandle(handle); + } + // Today's kind of host copy, for the comparison. + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let mut buffer: Option = None; + let made = rig.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &buffer_desc(bytes as u64, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ); + if let (Ok(()), Some(buffer)) = (made, buffer) { + let speed = rig.copy_ms(&buffer, bytes as u64).ok(); + p.lines.push(format!("cost, for comparison: the card copies {mb} MB out of a shared buffer of today's kind in {} ms", ms(speed))); + } + } +} + +// The census: which of the title memory that has host copies today could +// be opened, and by which opening. + +/// Counts and bytes by kind, in the order of [`KINDS`]. +#[derive(Default, Clone, Copy)] +struct Tally([(u64, u64); 6]); + +const KINDS: [&str; 6] = [ + "private, committed whole (a part can be opened)", + "view memory, one run of a section (one placed buffer)", + "view memory, scattered pages", + "view memory with unmapped pages", + "private but not committed whole, or guarded", + "other", +]; + +fn kind_of(at: usize, len: usize, known: &mut Vec<(usize, usize)>) -> usize { + match cover(at, len) { + Cover::Run(..) => return 1, + Cover::Scattered => return 2, + Cover::Holes => return 3, + Cover::None => {} + } + let end = at + len; + if known.iter().any(|&(from, to)| from <= at && end <= to) { + return 0; + } + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + if n == 0 { + return 5; + } + let reach = (info.BaseAddress as usize).saturating_add(info.RegionSize); + if info.Type == mem::MEM_PRIVATE && info.State == mem::MEM_COMMIT && info.Protect == mem::PAGE_READWRITE { + known.push((info.BaseAddress as usize, reach)); + return if reach >= end { 0 } else { 4 }; + } + match info.Type { + mem::MEM_PRIVATE => 4, + mem::MEM_MAPPED => 3, + _ => 5, + } +} + +/// The census lines for `spans` (start, bytes, whether a window outside +/// buffers). +fn census_of(spans: &[(u64, u64, bool)]) -> Vec { + let mut known = Vec::new(); + let (mut buffers, mut windows) = (Tally::default(), Tally::default()); + for &(start, len, window) in spans { + let kind = kind_of(start as usize, len as usize, &mut known); + let tally = if window { &mut windows } else { &mut buffers }; + tally.0[kind].0 += 1; + tally.0[kind].1 += len; + } + let mut lines = Vec::new(); + for (name, tally) in [("title buffers", buffers), ("windows outside buffers", windows)] { + let all = tally.0.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)); + lines.push(format!("census, {name}: {} of {} MB", all.0, all.1 >> 20)); + for (kind, &(n, bytes)) in KINDS.iter().zip(&tally.0) { + if n > 0 { + lines.push(format!("census, {kind}: {n} of {} MB", bytes >> 20)); + } + } + } + let v = views(); + let (count, bytes) = (v.views.len(), v.views.values().map(|view| view.0 as u64).sum::()); + let pages = v.views.values().filter(|view| view.0 == K64).count(); + let big = v.views.values().map(|view| view.0).max().unwrap_or(0); + lines.push(format!( + "census, the title's views of physical pages: {count} of {} MB; {pages} of them one 64 KiB page; the longest {} MB", + bytes >> 20, + big >> 20 + )); + for &(_, bytes, committed) in &v.sections { + lines.push(format!( + "census, a section of {} MB, {}", + bytes >> 20, + if committed { "committed: it can be opened as one heap" } else { "reserved: refused as a heap until it is made with SEC_COMMIT" } + )); + } + lines +} + +/// With [`probe_level`] 2: one part of the title's own private memory +/// (the start of the biggest such title buffer, 4 MiB at most) is opened +/// for a moment, a buffer placed, 64 KiB read by the GPU and compared +/// with what the CPU reads there (the title may be writing it meanwhile: +/// the count of equal bytes is given), and all of it released. While the +/// heap stands (milliseconds) a `VirtualFree` of the title's on those +/// pages would fail. +fn real_part(spans: &[(u64, u64, bool)]) -> Vec { + let Some(host) = crate::host::host() else { + return Vec::new(); + }; + let mut known = Vec::new(); + let found = spans + .iter() + .filter(|s| !s.2 && s.1 >= 2 * K64 as u64) + .filter(|s| kind_of(s.0 as usize, s.1 as usize, &mut known) == 0) + .max_by_key(|s| s.1); + let Some(&(start, len, _)) = found else { + return vec!["the title's memory: no title buffer in private, committed memory to try".to_owned()]; + }; + let at = (start as usize).next_multiple_of(K64); + let bytes = ((start + len) as usize).saturating_sub(at).min(4 << 20) & !(K64 - 1); + if bytes == 0 || !private_whole(at, bytes) { + return vec!["the title's memory: the buffer found holds no whole 64 KiB page that is still committed".to_owned()]; + } + let mut lines = Vec::new(); + let (set, started) = (working_set_mb(), std::time::Instant::now()); + let opened = open(&host.device, From::Part(at, bytes)); + lines.push(format!( + "the title's memory, {} KiB at {at:#x} (of the title buffer {start:#x}+{len:#x}): {}; in {:.1} ms; working set {set} -> {} MB", + bytes >> 10, + hr(&opened), + started.elapsed().as_secs_f64() * 1000.0, + working_set_mb() + )); + if let Ok(heap) = &opened { + let placed = place(&host.device, heap, 0, bytes as u64); + lines.push(format!(" a buffer placed over it: {}", hr(&placed))); + if let (Ok(buffer), Ok(mut rig)) = (&placed, Rig::new(&host.device)) { + let mut before = vec![0u8; K64]; + crate::host::copy_mapped(before.as_mut_ptr(), at as *const u8, K64, false); + let got = rig.fetch(buffer, 0, K64); + let mut after = vec![0u8; K64]; + crate::host::copy_mapped(after.as_mut_ptr(), at as *const u8, K64, false); + match got { + Ok(got) => { + let equal = (0..K64).filter(|&i| got[i] == before[i] || got[i] == after[i]).count(); + let zeros = got.iter().filter(|&&b| b == 0).count(); + lines.push(format!( + " the GPU read 64 KiB of the title's own bytes: {equal} of {K64} equal to what the CPU read just before or just after ({zeros} of them zero)" + )); + } + Err(e) => lines.push(format!(" the GPU's read failed: {e}")), + } + } + } + lines +} + +/// Called once a second by the thread that submits, before a submission +/// (`host::sweep`): with [`probe_level`], the probe at the first call, the +/// census (on a thread of its own: it asks Windows about every copy) 30 +/// and 150 seconds later. +pub(crate) fn tick() { + if level() > 0 { + say(); + } + if probe_level() == 0 { + return; + } + static STARTED: AtomicU64 = AtomicU64::new(0); + static DONE: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms().max(1); + let started = match STARTED.compare_exchange(0, now, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => { + let Some(host) = crate::host::host() else { + return; + }; + let mb = std::env::var("VICTORY_INPLACE_PROBE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64usize); + let took = std::time::Instant::now(); + let probe = probe(&host.device, &|| host.video_memory(), mb.min(1024)); + for line in &probe.lines { + tracing::info!("in place probe: {line}"); + } + tracing::info!("in place probe: took {:.0} ms", took.elapsed().as_secs_f64() * 1000.0); + now + } + Err(started) => started, + }; + let due = match DONE.load(Ordering::Relaxed) { + 0 => now >= started + 30_000, + 1 => now >= started + 150_000, + _ => false, + }; + if due { + let which = DONE.fetch_add(1, Ordering::Relaxed); + std::thread::spawn(move || { + let spans = crate::shadow::spans(); + for line in census_of(&spans) { + tracing::info!("in place {line}"); + } + if which == 0 && probe_level() >= 2 { + for line in real_part(&spans) { + tracing::info!("in place probe: {line}"); + } + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Views as the runtime tells them: a range inside one view, or over + /// views that continue each other in one section, is one run; over + /// views from elsewhere it is scattered; over a gap it has holes. + #[test] + fn views_say_what_one_placed_buffer_could_show() { + let mut views = BTreeMap::new(); + let at = 0x7_0000_0000usize; + views.insert(at, (4 * K64, 9, 16 * K64 as u64)); + // Continues the first in the section. + views.insert(at + 4 * K64, (2 * K64, 9, 20 * K64 as u64)); + // Follows in address, from elsewhere in the section. + views.insert(at + 6 * K64, (K64, 9, 3 * K64 as u64)); + // After a gap of one page. + views.insert(at + 8 * K64, (K64, 9, 4 * K64 as u64)); + assert_eq!(cover_in(&views, at + K64, 2 * K64), Cover::Run(9, 17 * K64 as u64)); + assert_eq!(cover_in(&views, at + K64, 5 * K64), Cover::Run(9, 17 * K64 as u64)); + assert_eq!(cover_in(&views, at, 7 * K64), Cover::Scattered); + assert_eq!(cover_in(&views, at + 6 * K64, 3 * K64), Cover::Holes); + assert_eq!(cover_in(&views, at + 7 * K64, K64), Cover::None); + assert_eq!(cover_in(&views, at - K64, 2 * K64), Cover::None); + } + + /// What the runtime forgets when memory is mapped anew. + #[test] + fn remapped_memory_forgets_its_views() { + let at = 0x7_4000_0000usize; + title_memory_view(at, 4 * K64, 77, 0); + title_memory_view(at + 4 * K64, K64, 77, 4 * K64 as u64); + assert_eq!(cover(at, 5 * K64), Cover::Run(77, 0)); + // One page inside the first view goes: the whole view is forgotten + // (the runtime maps and tells again what stays of it). + views_gone(at + K64, K64); + assert_eq!(cover(at, K64), Cover::None); + assert_eq!(cover(at + 4 * K64, K64), Cover::Run(77, 4 * K64 as u64)); + views_gone(at + 4 * K64, K64); + assert_eq!(cover(at + 4 * K64, K64), Cover::None); + } + + /// Only private memory committed whole, read-write, is taken for a part. + #[test] + fn only_private_memory_committed_whole_is_a_part() { + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE, mem::PAGE_NOACCESS).cast::(); + assert!(!base.is_null()); + assert!(!private_whole(base as usize, K64), "reserved only"); + mem::VirtualAlloc(base.cast(), 4 * K64, mem::MEM_COMMIT, mem::PAGE_READWRITE); + assert!(private_whole(base as usize, 4 * K64)); + assert!(private_whole(base as usize + K64, 2 * K64)); + assert!(!private_whole(base as usize, 5 * K64), "reaches into the reserved half"); + let mut old = 0; + mem::VirtualProtect(base.cast(), K64, mem::PAGE_READONLY, &mut old); + assert!(!private_whole(base as usize, 2 * K64), "a guarded page"); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + } + + pub(crate) fn warp() -> Option { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::*; + // SAFETY: plain DXGI queries and device creation on the software + // adapter; a card is never opened. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let desc = adapter.cast::().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + device + } + } + + /// The probe, whole, on the software adapter: the same calls the card + /// gets. The runtime's and the kernel's rules hold there; the card's + /// driver is what a run with `VICTORY_INPLACE_PROBE=1` adds. + #[test] + fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() { + let Some(device) = warp() else { return }; + if device.cast::().is_err() { + eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened"); + return; + } + let probe = probe(&device, &|| None, 4); + for line in &probe.lines { + eprintln!("in place probe: {line}"); + } + assert!(probe.part_reads, "the GPU reads private memory in place"); + assert!(probe.part_writes, "GPU writes land in private memory"); + assert!(probe.section_reads && probe.section_writes, "a committed section in place"); + assert!(probe.section_outlives_views, "the section's heap does not depend on views"); + assert!(probe.reserved_section_refused, "a reserved section is refused"); + } + + /// Stage 1's own call on the software adapter: a title buffer that + /// begins and ends off the 64 KiB lines is placed over its pages, the + /// GPU reads the buffer's bytes at the offset the views use, and its + /// write lands at the title's address. Memory that is not committed + /// whole is turned down without asking the host. + #[test] + fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() { + let Some(device) = warp() else { return }; + if device.cast::().is_err() { + return; + } + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::(); + let (start, len) = (base as u64 + K64 as u64 + 0x1230, 2 * K64 as u64 + 5); + let placed = place_part(&device, start, len).unwrap_or_else(|e| panic!("not placed: {e:?}")); + assert_eq!(placed.bias, 0x1230); + assert_eq!(placed.gpu, placed.buffer.GetGPUVirtualAddress() + 0x1230); + assert_eq!(placed.buffer.GetDesc().Width, 3 * K64 as u64, "the pages that hold the buffer"); + let mut rig = Rig::new(&device).unwrap(); + fill(start as *mut u8, len as usize, 7); + let got = rig.fetch(&placed.buffer, placed.bias, len as usize).unwrap(); + assert!(same(start as *const u8, &got), "the GPU reads the title buffer's bytes"); + rig.store(&placed.buffer, placed.bias + 16, &[0xa5; 64]).unwrap(); + assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); + drop(placed); + // Half of it decommitted: turned down, the host not asked. + assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0); + assert!(matches!(place_part(&device, start, len), Err(None))); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + } + + /// The census names each kind of memory. + #[test] + fn census_tells_private_memory_from_views() { + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as u64; + let view = 0x7_8000_0000u64; + title_memory_view(view as usize, 2 * K64, 5, 0); + title_memory_view(view as usize + 2 * K64, K64, 5, 9 * K64 as u64); + let lines = census_of(&[(base, 2 * K64 as u64, false), (base + 4 * K64 as u64, K64 as u64, true), (view, K64 as u64, true), (view, 3 * K64 as u64, false)]); + let text = lines.join("\n"); + assert!(text.contains("census, title buffers: 2 of"), "{text}"); + assert!(text.contains("census, private, committed whole (a part can be opened): 1 of"), "{text}"); + assert!(text.contains("census, view memory, scattered pages: 1 of"), "{text}"); + assert!(text.contains("census, view memory, one run of a section (one placed buffer): 1 of"), "{text}"); + views_gone(view as usize, 3 * K64); + mem::VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE); + } + } +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 3ec7b58..db53f11 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -15,15 +15,9 @@ //! share, [`console`] which console model the title sees. Planned: //! `present` (swap chain). -#[cfg(windows)] -mod address_map; -#[cfg(windows)] -mod breadcrumb; #[cfg(all(windows, feature = "diagnostics"))] mod capture; pub mod console; -#[cfg(windows)] -mod copy_pool; #[cfg(all(windows, feature = "diagnostics"))] mod copystat; pub mod descriptor; @@ -37,15 +31,13 @@ pub mod frame; mod host; #[cfg(windows)] mod indirect; -pub mod list; #[cfg(windows)] -mod mesh_emu; +mod inplace; +pub mod list; pub mod object; pub mod pipeline; #[cfg(windows)] mod primitive; -#[cfg(all(windows, feature = "diagnostics"))] -mod profile; pub mod query; pub mod queue; pub mod resource; @@ -55,6 +47,8 @@ mod sampler; #[cfg(windows)] pub mod shader_cache; #[cfg(windows)] +mod memory; +#[cfg(windows)] mod shadow; pub mod signature; #[cfg(windows)] @@ -65,4 +59,8 @@ mod watch; #[cfg(windows)] pub use host::on_failure; #[cfg(windows)] -pub use watch::{set_alias_lookup, title_memory_remapped, writing as kernel_will_write}; +pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; +#[cfg(windows)] +pub use watch::{ + title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write, +}; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index cf431b1..44c8965 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -32,7 +32,7 @@ const ALLOCATOR_IIDS: [Iid; 4] = [ /// The list interfaces up to `ID3D12GraphicsCommandList6` (the table has /// all their slots): those whose ids are the same as on PC, the console's -/// own List5 and List6 (Grand Theft Auto VI asks for List6), then the +/// own List5 and List6 (the title asks for List6), then the /// device child's. const LIST_IIDS: [Iid; 10] = [ guid( @@ -106,7 +106,7 @@ struct List { graphics_root_headers: [u32; 128], compute_root_headers: [u32; 128], pipeline_shadow: [u32; 8], - /// Newer titles' lists are larger: Grand Theft Auto VI's state flush + /// Newer titles' lists are larger: the title's state flush /// (title+0x32786) copies a pipeline's 32 bytes to +0x544..+0x564 and /// tests +0x548, so its layout runs past 0x560. Its size is unknown; /// this keeps our fields clear of whatever the title writes there. @@ -119,6 +119,22 @@ struct List { host: Option, #[cfg(windows)] state: std::sync::Mutex, + /// The parts of the recording before `host`, in order, each closed: the + /// list is cut at its waits for memory values ([`cut`]). + #[cfg(windows)] + earlier: Vec, + /// The waits recorded before the first work of `host`: the queue stands + /// at them before it runs `host`. + #[cfg(windows)] + gate: Vec, +} + +/// One part of a title list cut at its waits: the waits the queue stands +/// at, then the host list that runs once they are met. +#[cfg(windows)] +struct Part { + waits: Vec, + host: crate::host::HostList, } const _: () = assert!(offset_of!(List, put) == 0x18); const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560); @@ -128,9 +144,30 @@ const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560); #[cfg(windows)] fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State)) { let Some(list) = host_list(this) else { return }; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); // SAFETY: the title passes one of our lists. let state = unsafe { &(*this.cast::()).state }; f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner())); + #[cfg(feature = "diagnostics")] + crate::copystat::recorded(started); +} + +/// The submission of `lists` has run: each gives its descriptor tables' +/// slots back ([`crate::draw::State::tables_done`]). A list cut at waits +/// keeps them: its state goes with its last part. +#[cfg(windows)] +pub(crate) fn tables_done(lists: &[This]) { + for &this in lists { + if this.is_null() { + continue; + } + // SAFETY: the title passes our lists. + let list = unsafe { &*this.cast::() }; + if list.earlier.is_empty() { + list.state.lock().unwrap_or_else(|e| e.into_inner()).tables_done(); + } + } } /// The host list behind a title list, if there is a host GPU. @@ -143,6 +180,317 @@ pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { unsafe { (*this.cast::()).host.as_ref() } } +/// The host side of a submitted list, taken from it: a queue that waits +/// for a fence runs it later, and the title may reset the list meanwhile. +/// With it go the upload memory and the dynamic descriptor slots its +/// commands name, kept until it has run. +#[cfg(windows)] +pub(crate) struct Detached { + host: crate::host::HostList, + _uploads: Vec>, + _state: crate::draw::State, +} + +#[cfg(windows)] +impl Detached { + pub(crate) fn host(&self) -> &crate::host::HostList { + &self.host + } +} + +/// A host list that has run and waits to be used again, and the bytes of +/// upload memory it keeps. +#[cfg(windows)] +struct Idle(crate::host::HostList, u64); + +// SAFETY: D3D12 objects are free-threaded, and an idle list is touched by +// nobody until it is taken out again. +#[cfg(windows)] +unsafe impl Send for Idle {} + +/// Host lists that have run, reset and ready to record: the host side of +/// a list a queue held, or of a part of a list cut at a wait, is taken +/// from the title's list at its submission, and the title's list needs +/// another. Each was made new and thrown away after its run: a hundred a +/// frame in gameplay, each two command allocators and two lists, and for +/// four in ten a budget and an argument buffer (run 61: "104 host lists +/// made 21.2 ms" a frame, and the graphics kernel's time to free them). +#[cfg(windows)] +static IDLE: std::sync::Mutex<(Vec, u64)> = std::sync::Mutex::new((Vec::new(), 0)); + +/// The most host lists kept idle, and the most upload memory they may keep +/// between them (a list keeps scratch chunks over a reset only while lists +/// do not share them, `VICTORY_SCRATCH_POOL=0`). +#[cfg(windows)] +const IDLE_MOST: (usize, u64) = (128, 256 << 20); + +/// Whether host lists that have run are used again (on by default; +/// `VICTORY_LIST_POOL=0`: each is made new and thrown away, as before). +#[cfg(windows)] +fn pools() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIST_POOL").is_none_or(|v| v != "0")) +} + +/// A host list open for recording: one that has run, as a title's list is +/// after its reset, or a new one. +#[cfg(windows)] +fn fresh_list() -> Option { + let idle = { + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + let taken = idle.0.pop(); + if let Some(Idle(_, bytes)) = &taken { + idle.1 -= bytes; + } + taken + }; + match idle { + Some(Idle(list, _)) => Some(list), + None => crate::host::host().and_then(|h| h.new_list().ok()), + } +} + +/// The host sides of lists whose submission has run (submissions are +/// waited for; `ran` names the ones it ran, by their place in `lists`): +/// what they held is let go, as before, and the host lists are reset and +/// kept for [`fresh_list`]. +#[cfg(windows)] +pub(crate) fn recycle(lists: Vec, ran: &[usize]) { + if !pools() { + return; + } + for (i, Detached { host, _uploads, _state }) in lists.into_iter().enumerate() { + // The descriptor slots and the upload memory its commands named. + drop(_state); + drop(_uploads); + if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 { + continue; + } + // As the title's reset does: what the list kept for its commands + // goes, its allocators stay. + host.reset(); + let bytes = host.scratch_kept(); + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + if idle.0.len() < IDLE_MOST.0 && idle.1 + bytes <= IDLE_MOST.1 { + idle.0.push(Idle(host, bytes)); + idle.1 += bytes; + } + } +} + +/// A wait for a memory value recorded into list `this`, with waits cut +/// into lists (`crate::queue::cuts`). On the console the queue runs the +/// list up to the wait, stands there until the value is in memory, and +/// runs on; the list's bottom-of-pipe writes before the wait are done by +/// then, and other queues may be waiting for exactly those. So the +/// recording is cut here: the host list so far is closed and kept as a +/// part of its own ([`Part`]), the title's calls record into a new host +/// list from here on, and the wait stands before that one. A submission +/// then gives the queue the parts in order ([`detach_parts`]). +/// +/// A wait before any work (the first call after a reset, or a wait right +/// after another) cuts nothing: it joins the waits before the current +/// host list. +/// shortcut: a bottom-of-pipe write is done when its part has run, not at +/// its place in the part: a queue waiting for it starts later than on the +/// console, never earlier, and nothing can wait for itself that way (a +/// part has no wait after its first work). +#[cfg(windows)] +fn cut(this: This, wait: ValueWait) { + if this.is_null() { + return; + } + // SAFETY: the title passes one of our lists; a list is recorded by one + // thread at a time and is not submitted while it records. + let list = unsafe { &mut *this.cast_mut().cast::() }; + let Some(current) = list.host.as_ref() else { + return; + }; + if current.untouched() { + list.gate.push(wait); + return; + } + let Some(fresh) = fresh_list() else { + // shortcut: without a new host list the wait stands before the part + // it was recorded in. + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("no host list for the part after a wait: the wait moves to the part's start")); + list.gate.push(wait); + return; + }; + current.close(); + static CUTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if CUTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + tracing::info!(parts = list.earlier.len() + 2, "a list is cut at a wait for a memory value"); + } + if let Some(done) = list.host.replace(fresh) { + let waits = std::mem::replace(&mut list.gate, vec![wait]); + list.earlier.push(Part { waits, host: done }); + } + // What the title set so far, on the new host list. + if let Some(host) = list.host.as_ref() { + list.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .replay(host); + } +} + +/// Whether list `this` recorded a wait for a memory value (with waits cut +/// into lists). +#[cfg(windows)] +pub(crate) fn cut_list(this: This) -> bool { + if this.is_null() { + return false; + } + // SAFETY: one of our lists, closed and submitted: nothing records + // into it. + let list = unsafe { &*this.cast::() }; + !list.earlier.is_empty() || !list.gate.is_empty() +} + +/// What a queue is given for submitted lists that were cut at their waits: +/// the waits it stands at, the host lists it runs once they are met, and +/// the order those run in. +#[cfg(windows)] +pub(crate) type Parts = Vec<(Vec, Vec, Vec)>; + +/// Takes the host sides of the submitted `lists`, part by part ([`cut`]), +/// and leaves each list a new, closed host list for its next reset, as +/// [`detach`] does. What comes back is in the order the queue runs it: a +/// new entry starts at every part that has waits; host lists without +/// waits join the entry before them. The list's upload memory and draw +/// state (its dynamic descriptor slots) go with its last part, which runs +/// last. +/// shortcut: a list the submission names a second time runs again only if +/// it has one part and that part is in the entry being filled; otherwise +/// the second naming is dropped (logged once). +#[cfg(windows)] +pub(crate) fn detach_parts(lists: &[This]) -> Parts { + let mut parts: Parts = vec![(Vec::new(), Vec::new(), Vec::new())]; + // The lists taken: where its one host list is (entry, place), or none + // for a list of several parts. + let mut seen: Vec<(This, Option<(usize, usize)>)> = Vec::new(); + for &this in lists { + if this.is_null() { + continue; + } + if let Some(&(_, at)) = seen.iter().find(|(t, _)| *t == this) { + match at { + Some((entry, place)) if entry + 1 == parts.len() => parts[entry].2.push(place), + _ => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!("a list named twice by a submission that waits for memory values runs once") + }); + } + } + continue; + } + let Some(fresh) = fresh_list() else { + continue; + }; + // A new host list is open; the title's next call on its list is a + // reset, which wants it closed. + fresh.close(); + // SAFETY: one of our lists, closed and submitted: nothing records + // into it until the title resets it. + let list = unsafe { &mut *this.cast_mut().cast::() }; + let Some(host) = list.host.replace(fresh) else { + continue; + }; + let earlier = std::mem::take(&mut list.earlier); + let gate = std::mem::take(&mut list.gate); + 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())); + let single = earlier.is_empty() && gate.is_empty(); + let mut pieces: Vec<(Vec, Detached)> = earlier + .into_iter() + .map(|part| { + ( + part.waits, + Detached { + host: part.host, + _uploads: Vec::new(), + _state: Default::default(), + }, + ) + }) + .collect(); + pieces.push(( + gate, + Detached { + host, + _uploads: uploads, + _state: state, + }, + )); + let mut last = None; + for (waits, detached) in pieces { + if !waits.is_empty() { + parts.push((waits, Vec::new(), Vec::new())); + } + let entry = parts.len() - 1; + let (_, taken, order) = &mut parts[entry]; + let place = taken.len(); + order.push(place); + taken.push(detached); + last = Some((entry, place)); + } + seen.push((this, if single { last } else { None })); + } + // (The first entry is empty if the first list begins with a wait.) + parts.retain(|(_, taken, _)| !taken.is_empty()); + parts +} + +/// Takes the host sides of submitted lists (each once, however often the +/// submission names it) and leaves each list a new, closed host list for +/// its next reset: what was taken, and which of them run in what order. +#[cfg(windows)] +pub(crate) fn detach(lists: &[This]) -> (Vec, Vec) { + let mut taken: Vec<(This, Detached)> = Vec::new(); + let mut order = Vec::new(); + for &this in lists { + if this.is_null() { + continue; + } + if let Some(i) = taken.iter().position(|(t, _)| *t == this) { + order.push(i); + continue; + } + let Some(fresh) = fresh_list() else { + continue; + }; + // A new host list is open; the title's next call on its list is a + // reset, which wants it closed. + fresh.close(); + let list = this.cast_mut().cast::(); + // SAFETY: one of our lists, closed and submitted: nothing records + // into it until the title resets it. + let (host, uploads, state) = unsafe { + let Some(host) = (*list).host.replace(fresh) else { + continue; + }; + 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())); + (host, uploads, state) + }; + order.push(taken.len()); + taken.push(( + this, + Detached { + host, + _uploads: uploads, + _state: state, + }, + )); + } + (taken.into_iter().map(|(_, d)| d).collect(), order) +} + pub(crate) extern "system" fn create_allocator( _: This, kind: u32, @@ -162,11 +510,11 @@ pub(crate) extern "system" fn create_list( _nodes: u32, kind: u32, allocator: This, - _pipeline: This, + pipeline: This, iid: *const Iid, out: *mut This, ) -> HRESULT { - new_list(kind, allocator, iid, out) + new_list(kind, allocator, pipeline, iid, out) } /// The console's list creation: type, flags, node mask and barrier batch @@ -184,7 +532,7 @@ pub(crate) extern "system" fn create_list_x( _: This, desc: *const ListDesc, allocator: This, - _pipeline: This, + pipeline: This, iid: *const Iid, out: *mut This, ) -> HRESULT { @@ -193,10 +541,18 @@ pub(crate) extern "system" fn create_list_x( return E_INVALIDARG; }; tracing::debug!(?desc, "console command list"); - new_list(desc.kind, allocator, iid, out) + new_list(desc.kind, allocator, pipeline, iid, out) } -fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRESULT { +/// `pipeline` is the list's initial pipeline (null: none), bound until the +/// title sets another, as after a reset. +fn new_list( + kind: u32, + allocator: This, + pipeline: This, + iid: *const Iid, + out: *mut This, +) -> HRESULT { if allocator.is_null() { return E_INVALIDARG; } @@ -224,8 +580,18 @@ fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRES } }), #[cfg(windows)] - state: Default::default(), + state: { + let mut state = crate::draw::State::default(); + state.set_pipeline(pipeline); + std::sync::Mutex::new(state) + }, + #[cfg(windows)] + earlier: Vec::new(), + #[cfg(windows)] + gate: Vec::new(), }); + #[cfg(not(windows))] + let _ = pipeline; object::hand_out(LIST, list, iid, &LIST_IIDS, out) } @@ -256,18 +622,31 @@ extern "system" fn close(this: This) -> HRESULT { if let Some(host) = host_list(this) { host.close(); } - #[cfg(not(windows))] - let _ = this; S_OK } extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT { if allocator.is_null() { return E_INVALIDARG; } + // A wait recorded and never submitted goes with the recording. + VALUE_WAITS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|&(list, _)| list != this as usize); // Every submission of the list has run (submissions are waited for). // SAFETY: the title passes one of our lists. let uploads = unsafe { &(*this.cast::()).uploads }; uploads.lock().unwrap_or_else(|e| e.into_inner()).clear(); + // The parts of a recording that was cut and never submitted go with it + // (a submission takes the parts it runs). + #[cfg(windows)] + { + // SAFETY: the title passes one of our lists, and neither records + // into it nor submits it during its reset. + let list = unsafe { &mut *this.cast_mut().cast::() }; + list.earlier.clear(); + list.gate.clear(); + } #[cfg(windows)] with_state(this, |host, state| { host.reset(); @@ -333,7 +712,13 @@ fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option { first: if b.first.is_null() { b.first } else { - host(b.first)? + // A depth texture's unordered access is its colour twin's + // (the host gives the depth texture none): the barrier is + // on the texture shaders write. + match crate::resource::twin_resource(b.first) { + Some(twin) => twin.as_raw().cast_const().cast(), + None => host(b.first)?, + } }, ..*b }), @@ -343,7 +728,6 @@ fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option { /// An unordered access barrier on every resource: earlier shader writes /// finish before later work reads or writes. -#[cfg(windows)] const UAV_BARRIER: Barrier = Barrier { kind: 2, flags: 0, @@ -354,8 +738,6 @@ const UAV_BARRIER: Barrier = Barrier { /// Returns the console's barrier "actions" (none). extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 { - #[cfg(not(windows))] - let _ = (this, count, barriers); #[cfg(windows)] if let Some(list) = host_list(this) && !barriers.is_null() @@ -372,9 +754,10 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some() }) { host.push(UAV_BARRIER); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::WaitsForBuffers, 1); } if !host.is_empty() { - list.flush_barriers(); use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; const _: () = assert!(size_of::() == size_of::()); // SAFETY: the same layout; borrowed resource pointers, never @@ -399,21 +782,7 @@ pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: if let Some((texture, before)) = list.transition(resource, state) { let state = crate::host::legal_state(texture, state); let barrier = crate::host::transition(texture, State(before as i32), State(state as i32)); - list.queue_barrier(barrier); - } -} - -/// Moves a shadow buffer to the state required by its next GPU use. -#[cfg(windows)] -pub(crate) fn ensure_shadow_state( - list: &crate::host::HostList, - shadow: &std::sync::Arc, - state: u32, -) { - use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; - if let Some((buffer, before)) = list.transition_shadow(shadow, state) { - let barrier = crate::host::transition(&buffer, State(before as i32), State(state as i32)); - // SAFETY: an open list and a live shadow buffer. + // SAFETY: an open list and a live texture. unsafe { list.list.ResourceBarrier(&[barrier]) }; } } @@ -456,95 +825,49 @@ extern "system" fn copy_buffer_region( let _ = (this, dst, dst_offset, src, src_offset, len); } +/// Whether one of two resources is a target in a stand-in format and the +/// other is not ([`crate::resource::target_format`]): their texels differ +/// in size, so the host cannot copy between them (logged once). +#[cfg(windows)] +fn unlike(dst: This, src: This) -> bool { + let unlike = crate::resource::stands_in(dst) != crate::resource::stands_in(src); + if unlike { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(?dst, ?src, "copy between a stand-in target and title-format texels skipped") + }); + } + unlike +} + extern "system" fn copy_resource(this: This, dst: This, src: This) { #[cfg(windows)] { let Some(list) = host_list(this) else { return; }; - if let (Some(dst_copy), Some(src_copy)) = ( - crate::resource::host_copy(dst), - crate::resource::host_copy(src), + if let (Some(to), Some(from)) = ( + crate::resource::host_resource(dst), + crate::resource::host_resource(src), ) { - let (to, from) = (&dst_copy.texture, &src_copy.texture); + if unlike(dst, src) { + return; + } + // A source the title fills itself is uploaded first (upstream + // PR #671): a copy read whatever the host texture held. if crate::texture::title_written(from) { crate::texture::upload(list, src, from); } + // Depth textures shaders also write: what they wrote, first. + list.twin_use(dst, false, true); + list.twin_use(src, false, false); ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); - list.flush_barriers(); + crate::texture::host_written(dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("copy resource {src:?} to {dst:?}")); - // SAFETY: live textures. - let (a, b) = unsafe { (to.GetDesc(), from.GetDesc()) }; - if a.Dimension == b.Dimension - && a.Width == b.Width - && a.Height == b.Height - && a.DepthOrArraySize == b.DepthOrArraySize - && a.MipLevels == b.MipLevels - { - crate::texture::host_written(dst); - // SAFETY: an open list and matching live textures. - unsafe { list.list.CopyResource(to, from) }; - } else { - use windows::Win32::Graphics::Direct3D12::{ - D3D12_RESOURCE_DIMENSION_TEXTURE3D, D3D12_TEXTURE_COPY_LOCATION, - D3D12_TEXTURE_COPY_LOCATION_0, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - }; - let start = dst_copy.mip_drop().max(src_copy.mip_drop()); - let end = dst_copy.title_mips.min(src_copy.title_mips); - let slices = if a.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { - 1 - } else { - u32::from(a.DepthOrArraySize.min(b.DepthOrArraySize)) - }; - let mut copied = false; - for slice in 0..slices { - for mip in start..end { - let console_dst = slice * dst_copy.title_mips + mip; - let console_src = slice * src_copy.title_mips + mip; - let (Some(dst_sub), Some(src_sub)) = ( - dst_copy.host_subresource(console_dst), - src_copy.host_subresource(console_src), - ) else { - continue; - }; - let dst_mip = dst_sub % dst_copy.host_mips(); - let src_mip = src_sub % src_copy.host_mips(); - if (a.Width >> dst_mip).max(1) != (b.Width >> src_mip).max(1) - || (u64::from(a.Height) >> dst_mip).max(1) - != (u64::from(b.Height) >> src_mip).max(1) - { - continue; - } - let to_location = D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: a borrowed pointer the location never releases. - pResource: unsafe { std::mem::transmute_copy(to) }, - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: dst_sub, - }, - }; - let from_location = D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: as above. - pResource: unsafe { std::mem::transmute_copy(from) }, - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: src_sub, - }, - }; - copied = true; - // SAFETY: an open list and matching surviving subresources. - unsafe { - list.list - .CopyTextureRegion(&to_location, 0, 0, 0, &from_location, None) - }; - } - } - if copied { - crate::texture::host_written(dst); - } - } + // SAFETY: an open list and live textures. + 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), @@ -595,19 +918,42 @@ extern "system" fn copy_texture_region( else { return; }; - let Some(dst_copy) = crate::resource::host_copy(dst.resource) else { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!("texture to buffer copies not implemented")); + let Some(to) = crate::resource::host_resource(dst.resource) else { + // Texture to buffer: a read back. The list copies the texels + // into a host buffer of ours; once it has run they go to the + // title's buffer (`HostList::defer_read_back`). + // The title reads two tiny float targets back every frame (5x1 + // and 1x1 RGBA32F, 80 and 16 bytes: run 90), and read a buffer + // nobody wrote. `VICTORY_READ_BACK=0` leaves them unmade, as + // before. + static COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let made = read_back(list, dst, x, y, z, src, source_box); + if n <= 16 || n.is_multiple_of(4096) || made.is_err() { + static REFUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if made.is_err() && REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 16 { + return; + } + let source = crate::resource::host_resource(src.resource).map(|r| { + // SAFETY: a live resource. + let d = unsafe { r.GetDesc() }; + format!("{}x{} f{} mips {}", d.Width, d.Height, d.Format.0, d.MipLevels) + }); + tracing::info!( + copies = n, + made = ?made, + source = ?source, + source_kind = src.kind, + destination_kind = dst.kind, + destination_offset = dst.footprint.offset, + destination_bytes = ?dst.footprint.bytes(), + "a texture to buffer copy (a read back)" + ); + } return; }; - let to = &dst_copy.texture; - let mut to_location = dst; - if dst.kind != FOOTPRINT { - let console_sub = dst.footprint.offset as u32; - let Some(host_sub) = dst_copy.host_subresource(console_sub) else { - return; - }; - to_location.footprint.offset = u64::from(host_sub); + if unlike(dst.resource, src.resource) { + return; } let mut from = src; let _upload; // keeps the source alive while this call records it @@ -635,23 +981,22 @@ extern "system" fn copy_texture_region( } _upload = buffer; } else { - let Some(src_copy) = crate::resource::host_copy(src.resource) else { - return; - }; - let texture = &src_copy.texture; - let console_sub = src.footprint.offset as u32; - let Some(host_sub) = src_copy.host_subresource(console_sub) else { + let Some(texture) = crate::resource::host_resource(src.resource) else { return; }; - from.footprint.offset = u64::from(host_sub); + list.twin_use(src.resource, false, false); if crate::texture::title_written(texture) { crate::texture::upload(list, src.resource, texture); } ensure_state(list, src.resource, COPY_SOURCE); from.resource = texture.as_raw().cast_const().cast(); } + // A depth texture shaders also write: what they wrote, first (the + // source above too). + list.twin_use(dst.resource, false, true); ensure_state(list, dst.resource, COPY_DEST); crate::texture::host_written(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::()); #[cfg(feature = "diagnostics")] @@ -678,7 +1023,6 @@ extern "system" fn copy_texture_region( } const _: () = assert!(size_of::() == size_of::()); - list.flush_barriers(); // SAFETY: an open list; both locations in the host's layout, naming // live resources; the box is the title's (same layout). unsafe { @@ -696,6 +1040,70 @@ extern "system" fn copy_texture_region( let _ = (this, dst, x, y, z, src, source_box); } +/// Records a texture to buffer copy (a read back) of [`copy_texture_region`] +/// into `list`, or says why not. +#[cfg(windows)] +#[allow(clippy::too_many_arguments)] // the method's own arguments +fn read_back( + list: &crate::host::HostList, + dst: CopyLocation, + x: u32, + y: u32, + z: u32, + src: CopyLocation, + source_box: *const [u32; 6], +) -> Result<(), &'static str> { + use windows::Win32::Graphics::Direct3D12::D3D12_BOX; + use windows::core::Interface; + const FOOTPRINT: u32 = 1; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_READ_BACK").is_none_or(|v| v != "0")) { + return Err("switched off"); + } + if dst.kind != FOOTPRINT || src.kind == FOOTPRINT { + return Err("not a texture subresource into a placed footprint"); + } + if (x, y, z) != (0, 0, 0) { + return Err("a destination corner other than the footprint's"); + } + let host = crate::host::host().ok_or("no host")?; + let (footprint, [size, row, rows, pitch]) = dst.footprint.host_rows().ok_or("an unknown format")?; + // The title's buffer holds every row at its own pitch. + let bytes = pitch * (rows - 1) + row; + let data = buffer_range(dst.resource, dst.footprint.offset, bytes).ok_or("a destination outside its buffer")?; + let texture = crate::resource::host_resource(src.resource).ok_or("no host texture")?; + let buffer = host.read_back_buffer(size).ok_or("no read-back buffer")?; + // As a texture source of any copy: what shaders wrote to a depth twin + // and what the title wrote itself first, then the state. + list.twin_use(src.resource, false, false); + if crate::texture::title_written(texture) { + crate::texture::upload(list, src.resource, texture); + } + ensure_state(list, src.resource, COPY_SOURCE); + let mut from = src; + from.resource = texture.as_raw().cast_const().cast(); + let mut to = dst; + to.resource = buffer.as_raw().cast_const().cast(); + to.footprint = footprint; + let host_box = (!source_box.is_null()).then(|| source_box.cast::()); + #[cfg(feature = "diagnostics")] + list.note_op(|| { + format!( + "read back of {:?} sub {} into buffer {:?}+{:#x}: {rows} rows of {row} bytes", + src.resource, src.footprint.offset as u32, dst.resource, dst.footprint.offset + ) + }); + // SAFETY: an open list; both locations in the host's layout (asserted + // in `copy_texture_region`), naming a live texture and our buffer, which + // the list keeps until it is reset; the box is the title's. + unsafe { + list.list + .CopyTextureRegion((&raw const to).cast(), 0, 0, 0, (&raw const from).cast(), host_box) + }; + list.defer_read_back(buffer, data, [row as usize, rows as usize, pitch as usize]); + Ok(()) +} + #[allow(clippy::too_many_arguments)] // the method's own arguments extern "system" fn copy_texture_region_x( this: This, @@ -720,18 +1128,11 @@ extern "system" fn resolve( ) { #[cfg(windows)] if let Some(list) = host_list(this) - && let (Some(dst_copy), Some(src_copy)) = ( - crate::resource::host_copy(dst), - crate::resource::host_copy(src), + && let (Some(to), Some(from)) = ( + crate::resource::host_resource(dst), + crate::resource::host_resource(src), ) { - let (Some(dst_sub), Some(src_sub)) = ( - dst_copy.host_subresource(dst_sub), - src_copy.host_subresource(src_sub), - ) else { - return; - }; - let (to, from) = (&dst_copy.texture, &src_copy.texture); use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Direct3D12::{ D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1, @@ -740,23 +1141,22 @@ extern "system" fn resolve( use windows::core::Interface; const RESOLVE_DEST: u32 = 0x1000; const RESOLVE_SOURCE: u32 = 0x2000; + if unlike(dst, src) { + return; + } + // Depth textures shaders also write: what they wrote, first. + list.twin_use(dst, false, true); + list.twin_use(src, false, false); ensure_state(list, dst, RESOLVE_DEST); ensure_state(list, src, RESOLVE_SOURCE); crate::texture::host_written(dst); - list.flush_barriers(); #[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. unsafe { let (a, b) = (to.GetDesc(), from.GetDesc()); - let dst_mip = dst_sub % u32::from(a.MipLevels).max(1); - let src_mip = src_sub % u32::from(b.MipLevels).max(1); - let dst_w = (a.Width >> dst_mip).max(1); - let dst_h = (u64::from(a.Height) >> dst_mip).max(1); - let src_w = (b.Width >> src_mip).max(1); - let src_h = (u64::from(b.Height) >> src_mip).max(1); - let format = DXGI_FORMAT(format as i32); - if (dst_w, dst_h) == (src_w, src_h) { + let format = if crate::resource::stands_in(dst) { a.Format } else { DXGI_FORMAT(format as i32) }; + if (a.Width, a.Height) == (b.Width, b.Height) { list.list .ResolveSubresource(to, dst_sub, from, src_sub, format); } else if let Ok(list1) = list.list.cast::() { @@ -764,8 +1164,8 @@ extern "system" fn resolve( let rect = RECT { left: 0, top: 0, - right: dst_w.min(src_w) as i32, - bottom: dst_h.min(src_h) as i32, + right: a.Width.min(b.Width) as i32, + bottom: a.Height.min(b.Height) as i32, }; list1.ResolveSubresourceRegion( to, @@ -821,14 +1221,19 @@ extern "system" fn clear_rtv( unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } }); const RENDER_TARGET: u32 = 0x4; - let Some(rtv) = host.rtv(texture, record.desc().as_ref()) else { - return; - }; + let rtv = host.rtv(Some(texture), record.desc().as_ref()); // SAFETY: an open list, a fresh view of a live texture. - ensure_state(list, record.resource, RENDER_TARGET); - list.flush_barriers(); - // SAFETY: an open list, a fresh view of a live texture. - unsafe { list.list.ClearRenderTargetView(rtv, color, rects) }; + unsafe { + if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; + list.list.ResourceBarrier(&[crate::host::transition( + texture, + State(before as i32), + State(RENDER_TARGET as i32), + )]); + } + list.list.ClearRenderTargetView(rtv, color, rects); + } } #[cfg(not(windows))] let _ = (this, handle, color, count, rects); @@ -863,18 +1268,18 @@ extern "system" fn clear_dsv( unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } }); const DEPTH_WRITE: u32 = 0x10; + // A depth texture shaders also write: what they wrote, first (the + // clear may be of one slice or of some rectangles). + list.twin_use(record.resource, false, true); ensure_state(list, record.resource, DEPTH_WRITE); + if crate::resource::depth_and_unordered(record.resource) { + crate::resource::DEPTH_UNORDERED[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } let dsv = host.dsv(texture, record.depth_desc().as_ref()); - list.flush_barriers(); // SAFETY: an open list, a fresh view of a live texture. unsafe { - list.list.ClearDepthStencilView( - dsv, - D3D12_CLEAR_FLAGS(flags as i32 & 3), - depth, - stencil, - rects, - ) + list.list + .ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects) }; } #[cfg(not(windows))] @@ -987,31 +1392,11 @@ extern "system" fn set_pipeline(this: This, pipeline: This) { let _ = this; } -/// Records a global UAV barrier on `this`'s host list so earlier shader -/// writes finish before later GPU work starts. -fn wait_for_shader_writes(this: This) { - #[cfg(windows)] - if let Some(list) = host_list(this) { - use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; - // SAFETY: `Barrier` matches `D3D12_RESOURCE_BARRIER` in layout, and - // `UAV_BARRIER` names no resource (`first` is null). - let barrier = - unsafe { std::mem::transmute::(UAV_BARRIER) }; - // SAFETY: `list.list` is an open host command list. - unsafe { list.list.ResourceBarrier(&[barrier]) }; - } - #[cfg(not(windows))] - let _ = this; -} - /// Pipeline syncs: waits for earlier work and cache flushes, at the top or -/// bottom of the pipe `(flags, control, address, size)`. Within a single -/// command list, earlier shader writes must finish before later dispatches -/// or draws read or write the same resources, so record a UAV barrier on -/// the host list. -extern "system" fn sync(this: This, _flags: u32, _control: u32, _address: u64, _size: u64) { - wait_for_shader_writes(this); -} +/// bottom of the pipe `(flags, control, address, size)`. Host lists order +/// their own work and every submission is waited for, so there is nothing +/// to do. +extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {} /// Reset with console flags `(allocator, pipeline, flags)`; the flags only /// tune the console's command memory. @@ -1021,15 +1406,12 @@ extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: /// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list /// owns until it is reset, which the CPU writes and the GPU reads at the -/// same address; null on failure. Grand Theft Auto VI's BVH builder puts +/// same address; null on failure. The title's BVH builder puts /// its instance descriptions there (and wrote through our old /// `E_NOTIMPL` as a pointer). extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 { let align = usize::try_from(alignment).unwrap_or(0).max(16); - let Some(len) = usize::try_from(size) - .ok() - .and_then(|s| s.checked_add(align)) - else { + let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else { return std::ptr::null_mut(); }; if this.is_null() || !align.is_power_of_two() { @@ -1042,23 +1424,20 @@ extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mu // SAFETY: the title passes one of our lists. let uploads = unsafe { &(*this.cast::()).uploads }; // Moving the vector keeps its heap block where it is. - uploads - .lock() - .unwrap_or_else(|e| e.into_inner()) - .push(block); + uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block); at } /// 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. +/// the pipeline; depth order and shading rate hints): any arguments, +/// nothing returned. extern "system" fn ignored_state(_: This) {} /// The title's draw state (decision 0007, step 3), kept for its draws or /// 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; @@ -1080,30 +1459,24 @@ mod state { count: u32, viewports: *const D3D12_VIEWPORT, ) { - if let Some(list) = host_list(this) { - crate::draw::viewports(list, items(viewports, count)); - } + // (Through the draw state, which keeps them for the host list + // that continues this one after a cut: `State::replay`.) + with_state(this, |list, s| s.set_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.set_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) { + with_state(this, |list, s| { // SAFETY: the title passes four floats or null. - crate::draw::blend_factor(list, unsafe { factor.as_ref() }); - } + s.set_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.set_stencil_ref(list, reference)); } pub(super) extern "system" fn depth_bounds(this: This, min: f32, max: f32) { - if let Some(list) = host_list(this) { - crate::draw::depth_bounds(list, min, max); - } + with_state(this, |list, s| s.set_depth_bounds(list, min, max)); } pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) { with_state(this, |_, s| s.set_heaps(items(heaps, count))); @@ -1218,14 +1591,9 @@ mod state { } with_state(this, |list, s| s.dispatch_mesh(list, x)); } - /// `DispatchMeshX(x, flags, indirect arguments, payload)`. With - /// `indirect` set, the group counts are in GPU memory at that title - /// address: one mesh dispatch record, `x, y, z` (12 bytes), run as an - /// indirect execution of one record like ExecuteIndirect's mesh signature, - /// so earlier GPU work that wrote the counts is seen. - /// shortcut: the record layout is assumed to be the mesh dispatch - /// arguments the title's ExecuteIndirect signatures use, and `x` is - /// ignored then; not yet checked against the title. + /// `DispatchMeshX(x, flags, indirect arguments, payload)`. + /// shortcut: dispatches whose group count is in GPU memory (indirect) + /// are dropped; make them ExecuteIndirect when the title uses them. pub(super) extern "system" fn dispatch_mesh_x( this: This, x: u32, @@ -1235,29 +1603,12 @@ mod state { ) { super::count_draw(); if indirect != 0 { - let mut ran = false; - with_state(this, |list, s| { - ran = s.execute_indirect(list, (MESH_INDIRECT, MESH_RECORD, 1), indirect, None); - }); - if !ran { - super::INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::info!( - address = format!("{indirect:#x}"), - "an indirect mesh dispatch dropped (first time)" - ) - }); - } + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped")); return; } with_state(this, |list, s| s.dispatch_mesh(list, x)); } - /// The indirect argument kind of a mesh dispatch - /// (`State::execute_indirect`). - const MESH_INDIRECT: u32 = 10; - /// Bytes of one mesh dispatch record: three u32 group counts. - const MESH_RECORD: u32 = 12; pub(super) extern "system" fn draw_indexed( this: This, indices: u32, @@ -1293,8 +1644,8 @@ mod state { pub(super) use super::ignored_state as heaps; pub(super) use super::ignored_state as index_buffer; pub(super) use super::ignored_state as scissors; - pub(super) use super::ignored_state as depth_bounds; pub(super) use super::ignored_state as stencil_ref; + pub(super) use super::ignored_state as depth_bounds; pub(super) use super::ignored_state as targets; pub(super) use super::ignored_state as topology; pub(super) use super::ignored_state as vertex_buffers; @@ -1314,7 +1665,7 @@ extern "system" fn draw(_: This) { } /// `ExecuteIndirect(signature, max count, arguments, offset, count buffer, -/// offset)`. Grand Theft Auto VI's signatures (title+0x2479466, 2026-11-24) +/// offset)`. The title's signatures (title+0x2479466, 2026-11-24) /// hold one argument each: draw (stride 16), indexed draw (20), dispatch /// (12), mesh dispatch (12), and the console's single-pass dispatch, type /// 105 (stride 12: the three group counts; its flags live in the @@ -1336,25 +1687,15 @@ extern "system" fn execute_indirect( return; }; let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset); - #[cfg(windows)] let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset); - #[cfg(not(windows))] - let _ = (this, count_offset); - #[cfg(windows)] let mut ran = false; - #[cfg(not(windows))] - let ran = false; #[cfg(windows)] if let ([[kind, ..]], Some(address)) = (args, address) && (count.is_null() || counter.is_some()) { const DISPATCH: u32 = 2; const DISPATCH_SINGLE: u32 = 105; - let kind = if *kind == DISPATCH_SINGLE { - DISPATCH - } else { - *kind - }; + let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind }; with_state(this, |list, s| { ran = s.execute_indirect(list, (kind, stride, max), address, counter); }); @@ -1386,7 +1727,6 @@ extern "system" fn execute_indirect( } /// Indirect executions dropped since the last call. -#[cfg(windows)] pub(crate) fn take_indirect() -> u64 { INDIRECT.swap(0, std::sync::atomic::Ordering::Relaxed) } @@ -1408,10 +1748,181 @@ 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) {} +/// A GPU wait for a memory value: the list's commands after it run when +/// the 32 or 64 bits at `address` compare as asked with `reference`. +#[derive(Clone, Copy, Debug)] +pub(crate) struct ValueWait { + address: u64, + comparison: u32, + reference: u64, + wide: bool, +} + +impl ValueWait { + /// Whether the memory holds what is waited for now. + /// shortcut: the comparison codes are taken to be the comparison + /// functions' (1 never .. 8 always, value against reference); one not + /// known counts as met, and so does memory that is not mapped. + /// + /// The value is read through the kernel, which reports memory that is + /// not there instead of faulting (as the copies of title memory are + /// read, `crate::host::copy_mapped`). Asking Windows first whether the + /// memory is committed (`VirtualQuery`) walks the page tables to the + /// end of the region: the title keeps these values in a 1.1 GB + /// allocation (0xd00000000), where one question took about 8 ms, and a + /// queue asks at every submission and every signal, for each queue that + /// stands at a wait (the title has five queues). That was + /// 1.0-2.2 s of every cutscene frame on the thread that submits (runs + /// 36-49: "between its submissions ... kernel"; 47 of 110 looks at + /// that thread in run 49 found it in this question). + /// `VICTORY_WAIT_ASK=1` asks first, as before. + pub(crate) fn met(&self) -> bool { + #[cfg(all(windows, feature = "diagnostics"))] + let started = std::time::Instant::now(); + let met = self.holds(); + #[cfg(all(windows, feature = "diagnostics"))] + { + use crate::copystat::{C, add}; + add(C::WaitChecks, 1); + add(C::WaitCheckNs, started.elapsed().as_nanos() as u64); + } + met + } + + fn holds(&self) -> bool { + let bytes = if self.wide { 8 } else { 4 }; + if self.address == 0 { + return true; + } + static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); + if *ASK.get_or_init(|| std::env::var_os("VICTORY_WAIT_ASK").is_some_and(|v| v == "1")) + && !crate::texture::committed(self.address as *const u8, bytes) + { + return true; + } + // The low `bytes` bytes; the rest stays zero. + let mut raw = [0u8; 8]; + if !crate::host::read_into(self.address as *const u8, &mut raw[..bytes]) { + return true; + } + self.holds_for(u64::from_le_bytes(raw)) + } + + /// Where the value waited for is: address and bytes. + #[cfg(windows)] + pub(crate) fn place(&self) -> (usize, usize) { + (self.address as usize, if self.wide { 8 } else { 4 }) + } + + /// Whether the wait is met with `value` at its address (its low half + /// for a 32-bit wait). + pub(crate) fn holds_for(&self, value: u64) -> bool { + let (value, reference) = if self.wide { + (value, self.reference) + } else { + (value & 0xFFFF_FFFF, self.reference & 0xFFFF_FFFF) + }; + match self.comparison { + 1 => false, + 2 => value < reference, + 3 => value == reference, + 4 => value <= reference, + 5 => value > reference, + 6 => value != reference, + 7 => value >= reference, + _ => true, + } + } +} + +/// The waits lists recorded since their last reset, by list. +static VALUE_WAITS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// The waits of the submitted `lists` that are not met yet (taken from +/// them): what the console's GPU would stop at. The title orders work +/// between its queues this way (the title: the compute queue's +/// lighting passes wait for a value the graphics queue's depth pass writes +/// at the bottom of the pipe; run at once, they read a cleared depth +/// buffer and nothing was lit). +/// shortcut: a wait holds its whole list (and submission) back, not only +/// the commands after it. +pub(crate) fn unmet_waits(lists: &[This]) -> Vec { + let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + let mut unmet = Vec::new(); + waits.retain(|&(list, wait)| { + if !lists.iter().any(|&l| l as usize == list) { + return true; + } + if !wait.met() { + unmet.push(wait); + } + false + }); + unmet +} + +/// The waits each of the submitted `lists` recorded (taken from them), +/// met or not, at the list's first place in the submission. +#[cfg(windows)] +pub(crate) fn waits_by_list(lists: &[This]) -> Vec> { + let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + let mut by = vec![Vec::new(); lists.len()]; + waits.retain(|&(list, wait)| { + match lists.iter().position(|&l| l as usize == list) { + Some(i) => { + by[i].push(wait); + false + } + None => true, + } + }); + by +} + +fn wait_for(this: This, address: u64, comparison: u32, reference: u64, wide: bool) { + let wait = ValueWait { + address, + comparison, + reference, + wide, + }; + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 12 { + tracing::info!( + address = format_args!("{address:#x}"), + comparison, + reference, + wide, + met = wait.met(), + "a list waits for a memory value" + ); + } + #[cfg(all(windows, feature = "diagnostics"))] + if let Some(host) = host_list(this) { + crate::capture::op(std::ptr::from_ref(host) as usize, || { + format!( + "WAIT VALUE at {address:#x} comparison {comparison} reference {reference:#x} wide {wide} met {}", + wait.met() + ) + }); + } + // The list is cut here, and the wait stands before what follows. + #[cfg(windows)] + if crate::queue::cuts() { + cut(this, wait); + return; + } + VALUE_WAITS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((this as usize, wait)); +} +extern "system" fn wait_value(this: This, address: u64, comparison: u32, reference: u64) { + wait_for(this, address, comparison, reference, false); +} +extern "system" fn wait_value64(this: This, address: u64, comparison: u32, reference: u64) { + wait_for(this, address, comparison, reference, true); +} /// The enhanced barriers `(group count, groups)`: buffer, texture and /// global barriers with layouts instead of states. Every host use of a @@ -1419,9 +1930,26 @@ extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _referen /// first, so only their ordering matters: one barrier on every shader /// write (the title's buffer barriers order compute passes). extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { + // Diagnostics: counted, and left out under `VICTORY_BARRIER_TEST=groups`. + #[cfg(all(windows, feature = "diagnostics"))] if count > 0 { - wait_for_shader_writes(this); + crate::copystat::add(crate::copystat::C::WaitsForGroups, 1); + if crate::copystat::barrier_test() & 1 != 0 { + return; + } } + #[cfg(windows)] + if count > 0 + && let Some(list) = host_list(this) + { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + // SAFETY: the same layout; no resource named. + let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; + // SAFETY: an open list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } + #[cfg(not(windows))] + let _ = (this, count); } /// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and @@ -1429,6 +1957,7 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { /// GPU timestamp instead (64-bit form), flag 2 the system timestamp. extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) { defer_write(this, address, Written::Value(u64::from(value)), 4); + value_written(this, address, u64::from(value)); } extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) { const GPU_TIMESTAMP: u32 = 1; @@ -1439,6 +1968,65 @@ extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, fl _ => Written::Value(value), }; defer_write(this, address, what, 8); + if let Written::Value(value) = what { + value_written(this, address, value); + } +} + +/// The title wrote a value at the bottom of the pipe (not a timestamp, not +/// a query result): listed (diagnostics), and with `VICTORY_CUT_WRITES=1` +/// the host list is cut right behind it, so that the value is stored when +/// the card has run the list up to there, as on the console, and not when +/// the whole list has run. Lists of other queues wait for these values +/// (the title: the compute list that builds the depth pyramid +/// waits for one, and the meshlet culling of the same frame reads that +/// pyramid). Off by default: every such write then ends a host list, and +/// each part is a submission of its own. +fn value_written(this: This, address: u64, value: u64) { + #[cfg(windows)] + { + if address == 0 || this.is_null() { + return; + } + #[cfg(not(feature = "diagnostics"))] + let _ = value; + #[cfg(feature = "diagnostics")] + if let Some(host) = host_list(this) { + crate::capture::op(std::ptr::from_ref(host) as usize, || { + format!("WRITE VALUE at {address:#x} value {value:#x}") + }); + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WRITES").is_some_and(|v| v == "1")) + || !crate::queue::cuts() + { + return; + } + // SAFETY: the title passes one of our lists; a list is recorded by + // one thread at a time and is not submitted while it records. + let list = unsafe { &mut *this.cast_mut().cast::() }; + let Some(current) = list.host.as_ref() else { + return; + }; + let Some(fresh) = fresh_list() else { + return; + }; + current.close(); + if let Some(done) = list.host.replace(fresh) { + // The part so far keeps its waits; nothing stands before the + // next one but this part itself. + let waits = std::mem::take(&mut list.gate); + list.earlier.push(Part { waits, host: done }); + } + if let Some(host) = list.host.as_ref() { + list.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .replay(host); + } + } + #[cfg(not(windows))] + let _ = (this, address, value); } fn defer_write(this: This, address: u64, what: Written, bytes: usize) { @@ -1506,7 +2094,7 @@ const METHODS: [(usize, *const ()); 52] = [ (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 + (72, wait_value64 as *const ()), // 0x240, 64 bits (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 @@ -1531,7 +2119,7 @@ const MORE_METHODS: [(usize, *const ()); 9] = [ /// base list, after the clears (0x198/0x1a0 as before) and before /// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8 /// on is two later (taken here as starting exactly at 0x1d8). Inferred from -/// Grand Theft Auto VI's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe +/// The title's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe /// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate /// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure). const fn newer_slot(slot: usize) -> usize { @@ -1541,7 +2129,7 @@ const fn newer_slot(slot: usize) -> usize { /// Methods only newer titles' lists have. 0x490: the enhanced barrier /// `(group count, groups)`, with 16-byte groups `(type, count, barriers)` /// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`, -/// called from Grand Theft Auto VI's state flush with its result unused. +/// called from the title's state flush with its result unused. /// shortcut: 0x470's purpose is unknown; ignored until a title shows it /// matters. const NEWER_METHODS: [(usize, *const ()); 3] = [ @@ -1598,7 +2186,7 @@ mod tests { (at(0x18), at(0x28), at(0x30)) }; assert!(put >= draw_limit && put >= api_limit); - // The console's ID3D12GraphicsCommandList6, as Grand Theft Auto VI asks. + // The console's ID3D12GraphicsCommandList6, as the title asks. let mut same = null; assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK); assert_eq!(same, list); @@ -1613,299 +2201,10 @@ mod tests { assert!(!p.is_null() && (p as usize).is_multiple_of(0x100)); // SAFETY: 40 bytes were handed out. unsafe { p.write_bytes(0xab, 40) }; - assert!( - allocate_upload(list, 8, 0x30).is_null(), - "not a power of two" - ); - assert_eq!(reset(list, allocator, null), S_OK); - assert!( - // SAFETY: the list is ours. - unsafe { &(*list.cast::()).uploads } - .lock() - .unwrap() - .is_empty() - ); - let release = |o: This| slot:: u32>(o, 0x10)(o); - assert_eq!(release(list), 0); - assert_eq!(release(allocator), 0); - } - - fn non_host_list(newer: bool) -> This { - let table = if newer { - &NEWER_LIST_FUNCTIONS - } else { - &LIST_FUNCTIONS - }; - Box::into_raw(Box::new(List { - object: Object::new(table), - kind: 0, - put: [0; 5], - reserved: [0; 64], - graphics_root_headers: [0; 128], - compute_root_headers: [0; 128], - pipeline_shadow: [0; 8], - newer: [0; 256], - uploads: Default::default(), - #[cfg(windows)] - host: None, - #[cfg(windows)] - state: Default::default(), - })) - .cast() - } - - #[test] - fn sync_is_safe_on_null_and_non_host_lists() { - type SyncFn = extern "system" fn(This, u32, u32, u64, u64); - type BarrierGroupsFn = extern "system" fn(This, u32, *const u8); - - let base = list_table(false); - assert_eq!(base[129], sync as *const ()); - assert_eq!(base[130], sync as *const ()); - let newer = list_table(true); - assert_eq!(newer[131], sync as *const ()); - assert_eq!(newer[132], sync as *const ()); - assert_eq!(newer[146], barrier_groups as *const ()); - - sync(std::ptr::null(), 1, 2, 0x1000, 64); - barrier_groups(std::ptr::null(), 1, std::ptr::null()); - - for (is_newer, slots) in [(false, [129usize, 130]), (true, [131usize, 132])] { - let list = non_host_list(is_newer); - for slot_index in slots { - let offset = slot_index * size_of::<*const ()>(); - slot::(list, offset)(list, 0, 0, 0, 0); - slot::(list, offset)(list, 0x3, 0x1, 0xdead_beef, 256); - } - if is_newer { - let offset = 146 * size_of::<*const ()>(); - slot::(list, offset)(list, 0, std::ptr::null()); - slot::(list, offset)(list, 2, std::ptr::null()); - } - assert_eq!(slot:: u32>(list, 0x10)(list), 0); - } - } - - #[cfg(windows)] - #[test] - fn sync_orders_dependent_compute_uav_dispatches() { - use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; - use windows::Win32::Graphics::Direct3D::ID3DBlob; - use windows::Win32::Graphics::Direct3D12::{ - D3D12_COMPUTE_PIPELINE_STATE_DESC, D3D12_SHADER_BYTECODE, ID3D12PipelineState, - ID3D12RootSignature, - }; - use windows::core::s; - - let Some(host) = crate::host::host() else { - return; - }; - - const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=2, b0), UAV(u0), UAV(u1)" -cbuffer Params : register(b0) { uint count; uint stage; }; -RWByteAddressBuffer buf_a : register(u0); -RWByteAddressBuffer buf_b : register(u1); -[RootSignature(RS)] -[numthreads(64, 1, 1)] -void main(uint3 id : SV_DispatchThreadID) { - if (id.x >= count) return; - if (stage == 0u) { - uint v = id.x ^ 0xA5A50001u; - for (uint k = 0u; k < 32u; ++k) { - v = v * 1664525u + 1013904223u; - } - buf_a.Store(id.x * 4u, v); - } else if (stage == 1u) { - uint rev = count - 1u - id.x; - uint v = buf_a.Load(rev * 4u); - buf_b.Store(id.x * 4u, v + 1u); - } else if (stage == 2u) { - uint rev = count - 1u - id.x; - uint v = buf_b.Load(rev * 4u); - buf_a.Store(id.x * 4u, v * 3u); - } else { - uint rev = count - 1u - id.x; - uint v = buf_a.Load(rev * 4u); - buf_b.Store(id.x * 4u, v ^ 0x55AA55AAu); - } -} -"#; - - let mut code: Option = None; - let mut errors: Option = None; - // SAFETY: valid static HLSL source and entry-point/target names. - let compiled = unsafe { - D3DCompile( - SOURCE.as_ptr().cast(), - SOURCE.len(), - s!("sync_ordering_test"), - None, - None, - s!("main"), - s!("cs_5_1"), - 0, - 0, - &mut code, - Some(&mut errors), - ) - }; - if let Err(e) = compiled { - let msg = errors - .map(|b| { - // SAFETY: the compiler error blob owns its bytes. - let slice = unsafe { - std::slice::from_raw_parts( - b.GetBufferPointer().cast::(), - b.GetBufferSize(), - ) - }; - String::from_utf8_lossy(slice).into_owned() - }) - .unwrap_or_default(); - panic!("D3DCompile failed ({e}): {msg}"); - } - let code = code.expect("compiled shader blob"); - // SAFETY: `code` owns valid DXBC bytes containing an embedded root signature. - let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { - let bytes = std::slice::from_raw_parts( - code.GetBufferPointer().cast::(), - code.GetBufferSize(), - ); - let root: ID3D12RootSignature = host.device.CreateRootSignature(0, bytes).unwrap(); - let pso = host - .device - .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - CS: D3D12_SHADER_BYTECODE { - pShaderBytecode: bytes.as_ptr().cast(), - BytecodeLength: bytes.len(), - }, - ..Default::default() - }) - .unwrap(); - (root, pso) - }; - - const COUNT: u32 = 65_536; - const GROUPS: u32 = COUNT / 64; - let bytes = u64::from(COUNT) * 4; - let (buf_a, ptr_a) = host.shared_buffer(bytes).expect("shared buffer A"); - let (buf_b, ptr_b) = host.shared_buffer(bytes).expect("shared buffer B"); - // SAFETY: `ptr_a` and `ptr_b` point to `bytes` mapped bytes each. - unsafe { - ptr_a.write_bytes(0, bytes as usize); - ptr_b.write_bytes(0, bytes as usize); - } - // SAFETY: live D3D12 buffer resources. - let (gpu_a, gpu_b) = - unsafe { (buf_a.GetGPUVirtualAddress(), buf_b.GetGPUVirtualAddress()) }; - - let null = std::ptr::null(); - let mut allocator = null; - assert_eq!( - create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), - S_OK - ); - let mut list = null; - assert_eq!( - create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), - S_OK - ); - let hl = host_list(list).expect("host list present when host GPU exists"); - - // `device::tests::newer_device_levels_are_the_same_device` may flip - // `device::newer()` in parallel, so inspect this list's own vtable. - // SAFETY: `list` starts with `Object` whose first pointer is its vtable. - let is_newer = unsafe { - std::ptr::eq( - *list.cast::<*const *const ()>(), - NEWER_LIST_FUNCTIONS.0.as_ptr(), - ) - }; - let (top_slot, bottom_slot) = if is_newer { - (newer_slot(129), newer_slot(130)) - } else { - (129, 130) - }; - - type SyncFn = extern "system" fn(This, u32, u32, u64, u64); - let sync_top = slot::(list, top_slot * size_of::<*const ()>()); - let sync_bottom = slot::(list, bottom_slot * size_of::<*const ()>()); - - // SAFETY: `hl.list` is an open list and `root`, `pso`, `buf_a`, `buf_b` outlive execution. - unsafe { - hl.list.SetComputeRootSignature(&root); - hl.list.SetPipelineState(&pso); - hl.list.SetComputeRootUnorderedAccessView(1, gpu_a); - hl.list.SetComputeRootUnorderedAccessView(2, gpu_b); - - let p0 = [COUNT, 0u32]; - hl.list - .SetComputeRoot32BitConstants(0, 2, p0.as_ptr().cast(), 0); - hl.list.Dispatch(GROUPS, 1, 1); - - sync_top(list, 0, 0, 0, 0); - - let p1 = [COUNT, 1u32]; - hl.list - .SetComputeRoot32BitConstants(0, 2, p1.as_ptr().cast(), 0); - hl.list.Dispatch(GROUPS, 1, 1); - - sync_bottom(list, 0x1, 0x2, 0x1000, 64); - - let p2 = [COUNT, 2u32]; - hl.list - .SetComputeRoot32BitConstants(0, 2, p2.as_ptr().cast(), 0); - hl.list.Dispatch(GROUPS, 1, 1); - - // `count == 0` is a no-op; `count > 0` orders pass 3 after pass 2. - barrier_groups(list, 0, std::ptr::null()); - barrier_groups(list, 1, std::ptr::null()); - - let p3 = [COUNT, 3u32]; - hl.list - .SetComputeRoot32BitConstants(0, 2, p3.as_ptr().cast(), 0); - hl.list.Dispatch(GROUPS, 1, 1); - } - - assert_eq!( - slot:: HRESULT>(list, 0x48)(list), - S_OK - ); - host.execute(&[hl]); - - // SAFETY: `host.execute` waited for GPU completion; both mappings cover `COUNT` u32s. - let (out_a, out_b) = unsafe { - ( - std::slice::from_raw_parts(ptr_a.cast::(), COUNT as usize), - std::slice::from_raw_parts(ptr_b.cast::(), COUNT as usize), - ) - }; - for i in 0..COUNT { - let mut v = i ^ 0xA5A5_0001; - for _ in 0..32 { - v = v.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - } - let expected_a = v.wrapping_add(1).wrapping_mul(3); - assert_eq!( - out_a[i as usize], expected_a, - "ordering mismatch in buf_a at {i}" - ); - - let rev = COUNT - 1 - i; - let mut v_rev = rev ^ 0xA5A5_0001; - for _ in 0..32 { - v_rev = v_rev.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - } - let expected_b = v_rev.wrapping_add(1).wrapping_mul(3) ^ 0x55AA_55AA; - assert_eq!( - out_b[i as usize], expected_b, - "ordering mismatch in buf_b at {i}" - ); - } - + assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two"); assert_eq!(reset(list, allocator, null), S_OK); + // SAFETY: the list is ours. + assert!(unsafe { &(*list.cast::()).uploads }.lock().unwrap().is_empty()); let release = |o: This| slot:: u32>(o, 0x10)(o); assert_eq!(release(list), 0); assert_eq!(release(allocator), 0); diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs new file mode 100644 index 0000000..c256367 --- /dev/null +++ b/crates/victory-gpu/src/memory.rs @@ -0,0 +1,319 @@ +//! Title memory by address, for translated shaders that read and write +//! through raw 40-bit addresses (`victory_shader::emit::SLOT_MEMORY`: the +//! console's ray-tracing structure builder and the programs that walk its +//! structures; the structures themselves lie in plain title memory, in no +//! buffer object). +//! +//! The copies are the ones every other access uses ([`crate::shadow`]: a +//! title buffer's copy, or the 4 MiB window of memory outside buffers), so +//! a root view and a raw address reach the same host bytes. This module +//! keeps what a shader needs to find them: +//! +//! - the **directory**: per 64 KiB page of title address space the number +//! of the copy that holds the page (0: none) and the page's byte offset +//! in it; one buffer for all lists, entries only ever go from empty to +//! filled; +//! - per view heap a run of slots with a raw unordered access view of each +//! numbered copy (slot 0 of the run: a null view, for pages without a +//! copy); +//! - the **faults**: the page numbers shaders found empty, read back here +//! once a frame, so the copies exist from the next frame on. A pointer a +//! shader takes out of memory cannot be known before it runs; the +//! addresses a dispatch is given as root views are made ready before it. +//! +//! **A page that is not there when a shader touches it is a lost access**: +//! the read gives 0, the store is dropped, and the fault note only helps +//! the next frame. For the structure builder that is the same as a dropped +//! stage, so before a dispatch the host makes ready everything it can see +//! the dispatch name: the whole copy around each root view, around each +//! pair of root constants that is a title address and around each root +//! constant that is one in 256-byte units (the builder passes structures +//! all three ways), and the 4 MiB after each (a structure may cross a +//! window's end). +//! shortcut: what a stage reaches only through pointers it reads out of +//! memory (InitHeaders' table of structure addresses, LoadInstances' +//! instance records) is not made ready unless something else named it; +//! the fault count in the log says whether that happens. The whole answer +//! is the extent of the title's allocation around an address, which the +//! memory module of the layer knows and this one does not ask yet. +//! +//! shortcut: a copy that is numbered is kept for the rest of the run, and +//! there are at most [`COPIES`] of them (4 MiB windows mostly: 4 GiB at +//! most). Every dispatch of such a shader brings all numbered copies up to +//! date and, if it can store, declares all of them written (the bytes are +//! compared on the CPU afterwards, as for any unordered access view): a +//! dirty-page mask written by the shader would bound both. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use victory_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES}; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::descriptor::host::HostHeap; +use crate::host::{HostList, host}; +use crate::shadow::Shadow; + +/// Copies that can be numbered (the run of heap slots is one longer). A +/// listed frame of the opening cutscene names about 50 windows. +const COPIES: u32 = 1023; +/// A window of memory outside buffers (`shadow.rs`). +const CELL: u64 = 4 << 20; +/// A directory page. +const PAGE: u64 = 1 << 16; + +struct Memory { + /// Buffer, its mapping, its GPU address. + directory: (ID3D12Resource, *mut u32, u64), + faults: (ID3D12Resource, *mut u32, u64), + /// Copy `n` is `copies[n - 1]`. + copies: Vec>, + /// Per host view heap (by address): the first slot of its run, and how + /// many copies have their view there. + heaps: HashMap, + /// The frame the faults were last read in. + frame: u64, + /// Pages asked for this frame that are not the title's memory. + refused: std::collections::HashSet, +} + +// SAFETY: the mappings are of buffers the struct owns; all access is under +// the mutex. +unsafe impl Send for Memory {} + +static MEMORY: Mutex> = Mutex::new(None); + +/// What a draw binds. +pub(crate) struct Ready { + pub(crate) directory: u64, + pub(crate) faults: u64, + /// The view heap slot of the null view; copy `n`'s view is `n` further. + pub(crate) base: u32, +} + +impl Memory { + fn new() -> Option { + let host = host()?; + let make = |dwords: u64, what: &str| { + let (buffer, data) = host.shared_buffer(dwords * 4)?; + crate::host::name(&buffer, || format!("title memory by address: {what}")); + // SAFETY: a fresh mapping of at least that many bytes. + unsafe { std::ptr::write_bytes(data, 0, (dwords * 4) as usize) }; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + Some((buffer, data.cast::(), gpu)) + }; + tracing::info!("title memory by address: a shader reads or writes through raw addresses"); + Some(Memory { + directory: make(u64::from(MEMORY_PAGES) * 2, "directory")?, + faults: make(u64::from(MEMORY_FAULTS), "faults")?, + copies: Vec::new(), + heaps: HashMap::new(), + frame: u64::MAX, + refused: Default::default(), + }) + } + + /// Gives the page of `address` its copy, if it has none and the memory + /// is the title's. + fn map(&mut self, address: u64) { + let page = address / PAGE; + // The last entry stays empty: addresses past the directory read it. + if page >= u64::from(MEMORY_PAGES) - 1 { + return; + } + // SAFETY: inside the directory's mapping. + let entry = unsafe { self.directory.1.add(page as usize * 2) }; + // SAFETY: as above. + if unsafe { entry.read() } != 0 { + return; + } + let start = page * PAGE; + // A shader's pointer, or a constant taken for an address, may be + // anything: only memory the title has. + if self.refused.contains(&page) { + return; + } + if !crate::texture::committed(start as *const u8, PAGE as usize) { + self.refused.insert(page); + return; + } + // The copy a root view at that address would get; a buffer that + // ends inside the page is passed over for what holds all of it. + let whole = |s: &Arc| s.offset_in(start).is_some_and(|_| s.left(start) >= PAGE); + let Some(shadow) = crate::shadow::find(start, 1) + .filter(whole) + .or_else(|| crate::shadow::find(start, PAGE).filter(whole)) + else { + return; + }; + // SAFETY: a live buffer. + let flags = unsafe { shadow.buffer.GetDesc() }.Flags; + if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { + return; + } + let n = match self.copies.iter().position(|c| Arc::ptr_eq(c, &shadow)) { + Some(n) => n, + None if self.copies.len() < COPIES as usize => { + self.copies.push(shadow.clone()); + let n = self.copies.len() - 1; + // Every page the copy holds whole, not only the one asked + // for: a structure is more than 64 KiB. + // shortcut: a page of a title buffer inside this one that + // has a copy of its own is given this copy too. + let (first, len) = shadow.span(); + let mut at = first.next_multiple_of(PAGE); + while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 { + // SAFETY: inside the directory's mapping. + let other = unsafe { self.directory.1.add((at / PAGE) as usize * 2) }; + // SAFETY: as above; the offset first, as below. + unsafe { + if other.read() == 0 { + other.add(1).write_volatile((at - first) as u32); + other.write_volatile(n as u32 + 1); + } + } + at += PAGE; + } + n + } + None => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros") + }); + return; + } + }; + let offset = shadow.offset_in(start).unwrap_or(0); + // The offset first: a shader that sees the number sees it too. + // SAFETY: inside the directory's mapping. + unsafe { + entry.add(1).write_volatile(offset as u32); + entry.write_volatile(n as u32 + 1); + } + } + + /// The pages shaders found empty since the last frame. + fn take_faults(&mut self) { + let mut pages = Vec::new(); + for i in 1..MEMORY_FAULTS as usize { + // SAFETY: inside the faults' mapping; the GPU may be writing, + // a number missed now is written again next frame. + let at = unsafe { self.faults.1.add(i) }; + // SAFETY: as above. + let page = unsafe { at.read_volatile() }; + if page != 0 { + pages.push(page); + // SAFETY: as above. + unsafe { at.write_volatile(0) }; + } + } + if !pages.is_empty() { + // Each is an access that read 0 or was dropped. + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 50 { + tracing::warn!( + pages = pages.len(), + first = format_args!("{:#x}", u64::from(pages[0]) * PAGE), + "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now" + ); + } + } + for page in pages { + self.map(u64::from(page) * PAGE); + } + } + + /// What a dispatch names: the copy around `address` and the 4 MiB + /// after it. + fn name(&mut self, address: u64) { + self.map(address); + self.map((address & !(CELL - 1)) + CELL); + } +} + +/// Before a draw whose shader reads title memory by address: what its +/// root arguments name gets its copies (`addresses`: its root views; +/// `constants`: its root constants, see the module), every numbered copy +/// has its view in `heap`'s run and is brought up to date when `list` is +/// submitted (and, with `writes`, copied back after). None if the host +/// cannot hold it; the draw is then dropped. +pub(crate) fn ready( + list: &HostList, + heap: &HostHeap, + addresses: &[u64], + constants: &[u32], + writes: bool, +) -> Option { + let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); + if guard.is_none() { + *guard = Memory::new(); + } + let m = guard.as_mut()?; + let frame = crate::frame::current(); + if m.frame != frame { + m.frame = frame; + m.refused.clear(); + m.take_faults(); + } + let numbered = m.copies.len(); + for &address in addresses { + m.name(address); + } + // A title address in two constants (low dword, then bits 32 to 39), or + // in one in 256-byte units. A constant that only looks like one names + // memory nothing reads; one that is not the title's memory is refused. + for (i, &c) in constants.iter().enumerate() { + if let Some(&high) = constants.get(i + 1) + && (1..=0xFF).contains(&high) + && c >= 0x1_0000 + { + m.name(u64::from(c) | u64::from(high) << 32); + } + if c >= 0x0100_0000 { + m.name(u64::from(c) << 8); + } + } + let key = std::ptr::from_ref(heap) as usize; + let (base, made) = match m.heaps.get(&key) { + Some(&run) => run, + None => { + // Held for the heap's life: not given back with a list's slots. + let base = heap.dynamic(COPIES + 1)?; + heap.null_raw_uav_at(base); + (base, 0) + } + }; + for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) { + let (_, len) = shadow.span(); + heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len); + } + m.heaps.insert(key, (base, m.copies.len() as u32)); + // Once per list, and for copies numbered since: the builder alone + // dispatches hundreds of times a frame. + // shortcut: a copy another list numbers meanwhile is brought up to date + // by that list's submission, which may run after this one's. + const READ: usize = usize::MAX - 0x6d; + const WRITE: usize = usize::MAX - 0x6e; + let first_read = list.first_use(READ); + let first_write = writes && list.first_use(WRITE); + for (n, shadow) in m.copies.iter().enumerate() { + let (start, len) = shadow.span(); + if first_read || n >= numbered { + shadow.refresh(list, start, len); + } + if writes && (first_write || n >= numbered) { + shadow.gpu_writes(list, start, len); + } + } + if first_read { + list.keep(&m.directory.0); + list.keep(&m.faults.0); + } + Some(Ready { + directory: m.directory.2, + faults: m.faults.2, + base, + }) +} diff --git a/crates/victory-gpu/src/mesh_emu.rs b/crates/victory-gpu/src/mesh_emu.rs deleted file mode 100644 index e4cb9a5..0000000 --- a/crates/victory-gpu/src/mesh_emu.rs +++ /dev/null @@ -1,103 +0,0 @@ -//! Shared GPU memory for compute + vertex mesh emulation. -//! -//! An emulated mesh pipeline first runs the translated mesh shader as -//! compute, writing packed primitive indices and attributes into `output`. -//! Its generated vertex shader then reads that memory by `SV_VertexID` and -//! feeds the title's pixel shader. The buffer is shared by every emulated -//! mesh dispatch, with direct dispatches split into chunks that fit. - -use std::sync::OnceLock; - -use crate::host::{Host, host, name}; -use windows::Win32::Graphics::Direct3D12::*; - -const OUTPUT_FALLBACK_SIZES: &[u64] = &[128 << 20, 64 << 20, 32 << 20, 16 << 20]; - -pub(crate) struct Buffers { - pub(crate) output: ID3D12Resource, - pub(crate) output_gpu: u64, - pub(crate) output_bytes: u64, - pub(crate) dummy_srv: ID3D12Resource, - pub(crate) dummy_srv_gpu: u64, -} - -// SAFETY: D3D12 resources are free-threaded. -unsafe impl Send for Buffers {} -// SAFETY: as above. -unsafe impl Sync for Buffers {} - -pub(crate) fn buffers() -> Option<&'static Buffers> { - static BUFFERS: OnceLock> = OnceLock::new(); - BUFFERS - .get_or_init(|| match make() { - Some(b) => Some(b), - None => { - tracing::warn!("no mesh emulation output buffer; emulated mesh dispatches dropped"); - None - } - }) - .as_ref() -} - -fn configured_output_bytes() -> Option { - let raw = std::env::var("VICTORY_MESH_BUFFER_MB").ok()?; - let mb = raw.trim().parse::().ok()?; - if (1..=1024).contains(&mb) { - Some(mb << 20) - } else { - tracing::warn!( - value = %raw, - "VICTORY_MESH_BUFFER_MB out of range (1..=1024); using default" - ); - None - } -} - -fn allocate_output(host: &Host) -> Option<(ID3D12Resource, u64)> { - if let Some(bytes) = configured_output_bytes() - && let Some(buf) = host.default_buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) - { - return Some((buf, bytes)); - } - for &bytes in OUTPUT_FALLBACK_SIZES { - if let Some(buf) = host.default_buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) { - return Some((buf, bytes)); - } - } - None -} - -fn make() -> Option { - let host = host()?; - let (output, output_bytes) = allocate_output(host)?; - let (dummy_srv, dummy_ptr) = host.upload_buffer(256)?; - // SAFETY: `dummy_ptr` points to 256 writable bytes of the live upload buffer. - unsafe { std::ptr::write_bytes(dummy_ptr, 0, 256) }; - name(&output, || format!("mesh emu output {output_bytes:#x}")); - name(&dummy_srv, || "mesh emu dummy_srv".into()); - // SAFETY: both are live buffer resources. - let (output_gpu, dummy_srv_gpu) = unsafe { - ( - output.GetGPUVirtualAddress(), - dummy_srv.GetGPUVirtualAddress(), - ) - }; - tracing::info!( - output_mb = output_bytes >> 20, - "mesh shader emulation output buffer ready" - ); - Some(Buffers { - output, - output_gpu, - output_bytes, - dummy_srv, - dummy_srv_gpu, - }) -} - -impl Buffers { - /// Maximum number of mesh thread groups that fit in `output` in one chunk. - pub(crate) fn group_cap(&self, group_bytes: u32) -> u32 { - (self.output_bytes / u64::from(group_bytes.max(4))).min(65_535) as u32 - } -} diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 2e9d1ac..60ed05c 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -4,7 +4,7 @@ //! types. //! //! Host pipelines are made on a pipeline's first draw, not at creation: -//! Grand Theft Auto VI creates some 60,000 pipelines in its first 20 +//! The title creates some 60,000 pipelines in its first 20 //! seconds and draws with a few dozen (decision 0007, step 3). Shader //! containers are shared by content hash and translated once, on first //! use (decision 0003). @@ -18,9 +18,7 @@ use std::collections::HashMap; use std::mem::offset_of; -#[cfg(windows)] -use std::sync::OnceLock; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, OnceLock}; use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, PIPELINE, Table, This, guid}; use crate::resource::PAGEABLE_IIDS; @@ -76,6 +74,29 @@ impl std::fmt::Debug for Shader { /// Every container seen, by full content hash. static SHADERS: Mutex>>> = Mutex::new(None); +/// For the memory lines: containers kept and their bytes, translations +/// kept and the bytes of their host code. None of them is ever let go. +static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// What the shader table and the pipeline library keep in memory: +/// containers and their bytes, translations and their bytes, the bytes of +/// the library's file (kept whole while the library lives) and what its +/// last save wrote. +#[cfg(windows)] +#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] +pub(crate) fn kept() -> [u64; 7] { + use std::sync::atomic::Ordering::Relaxed; + [ + KEPT[0].load(Relaxed), + KEPT[1].load(Relaxed), + KEPT[2].load(Relaxed), + KEPT[3].load(Relaxed), + library::BLOB.load(Relaxed), + library::SAVED.load(Relaxed), + library::TRIMMED_BYTES.load(Relaxed), + ] +} + /// The shared container for `bytes`. fn shader(stage: &'static str, bytes: &[u8]) -> Arc { let full = blake3::hash(bytes); @@ -84,6 +105,8 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc { .get_or_insert_with(HashMap::new) .entry(*full.as_bytes()) .or_insert_with(|| { + KEPT[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + KEPT[1].fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed); Arc::new(Shader { stage, hash: full.to_hex()[..16].to_owned(), @@ -100,26 +123,34 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc { pub(crate) struct Translated { pub(crate) host: victory_shader::emit::HostShader, pub(crate) used: Vec, + /// Whether the shader's code can store to buffer memory ([`stores`]); + /// true when its code is not known. + pub(crate) stores: bool, } #[cfg(windows)] impl Shader { - #[cfg(test)] - pub(crate) fn test_compute(translated: Translated) -> Arc { - Arc::new(Self { - stage: "compute", - hash: "test-compute".into(), - container: Vec::new(), - translated: OnceLock::from(Some(translated)), - }) - } - /// The translation, made on first use; a shader that does not /// translate is logged once. pub(crate) fn translated(&self) -> Option<&Translated> { self.translated .get_or_init(|| { - let done = translate(&self.container, self.stage); + let done = translate(&self.container); + // `VICTORY_SHADER_SAVE=`: each shader as the title gave it (`.cdxil`) and as + // translated (`.dxil`), by the hash crash reports name it with + if let Some(dir) = std::env::var_os("VICTORY_SHADER_SAVE") { + let dir = std::path::PathBuf::from(dir); + let _ = std::fs::create_dir_all(&dir); + let stem = format!("{}.{}", self.hash, self.stage); + let _ = std::fs::write(dir.join(format!("{stem}.cdxil")), &self.container); + if let Ok(t) = &done { + let _ = std::fs::write(dir.join(format!("{stem}.dxil")), &t.host.dxil); + } + } + if let Ok(t) = &done { + KEPT[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + KEPT[3].fetch_add(t.host.dxil.len() as u64, std::sync::atomic::Ordering::Relaxed); + } match &done { Ok(t) => tracing::info!( stage = self.stage, @@ -142,33 +173,172 @@ impl Shader { } #[cfg(windows)] -fn translate(container: &[u8], stage: &str) -> Result { - use victory_shader::emit::MeshMode; +fn translate(container: &[u8]) -> Result { use victory_shader::{Container, FourCC, HwStage}; - let mesh = if stage == "mesh" - && crate::host::host().is_some_and(crate::host::Host::emulate_mesh_shaders) - { - MeshMode::Emulate - } else { - MeshMode::Native - }; - let host = crate::shader_cache::host_shader(container, mesh)?; + // The translation depends on it (a view index past a capped heap). + crate::descriptor::host::probe_view_limit(); let c = Container::parse(container).map_err(|e| e.to_string())?; - let used = match c.part(FourCC::DXIL) { - Some(part) => victory_shader::native_programs(part.data) - .map_err(|e| e.to_string())? - .into_iter() - .find(|p| { - matches!( - p.stage, - HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs - ) - }) - .map(|p| p.used) - .unwrap_or_default(), + let programs = match c.part(FourCC::DXIL) { + Some(part) => victory_shader::native_programs(part.data).map_err(|e| e.to_string())?, None => Vec::new(), }; - Ok(Translated { host, used }) + let host = crate::shader_cache::host_shader(container)?; + let stores = programs.is_empty() || programs.iter().any(stores); + let used = programs + .into_iter() + .find(|p| { + matches!( + p.stage, + HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs + ) + }) + .map(|p| p.used) + .unwrap_or_default(); + Ok(Translated { host, used, stores }) +} + +/// The compute pipelines of the console's ray-tracing structure builder +/// (`XboxBvhBuilder.dll`; its programs are the ones with a spilled +/// user-data table) run **all or none**. Its stages feed each other +/// through memory: a stage that runs on what a dropped stage never wrote +/// computes its store offsets from garbage. The structures lie in plain +/// title memory, between the title's own objects, and a root view has no +/// size, so those stores land on the neighbours (run 98, with 14 of 35 +/// stages translated: the title died within a second of the first builder +/// submission, on pointers that had become bounding-box bit patterns). +/// +/// So a builder dispatch runs only while every builder pipeline the title +/// has created has a host pipeline; the first builder dispatch makes them +/// all on the spot instead of over the next frames (a stage "still being +/// made" would be a dropped stage). One that cannot be made turns the +/// builder off for the rest of the run. +/// +/// shortcut: and only with `VICTORY_BVH_BUILDER=1`, until a run has shown +/// the whole builder and the host side of title memory by address +/// (`memory.rs`) working on a card; nothing reads the structures before +/// the programs that walk them translate. +#[cfg(windows)] +struct Builder { + pipelines: Vec>, + /// Every one of `pipelines` has a host pipeline. + whole: bool, + /// One could not be made. + off: bool, +} + +#[cfg(windows)] +static BUILDER: Mutex = Mutex::new(Builder { + pipelines: Vec::new(), + whole: false, + off: false, +}); + +/// Whether `shaders` are a pipeline of the structure builder. +#[cfg(windows)] +fn of_builder(shaders: &[Arc]) -> bool { + use victory_shader::{Container, FourCC}; + let [shader] = shaders else { return false }; + if shader.stage != "compute" { + return false; + } + let Ok(c) = Container::parse(&shader.container) else { + return false; + }; + c.part(FourCC::DXIL) + .and_then(|part| victory_shader::native_programs(part.data).ok()) + .is_some_and(|programs| programs.iter().any(victory_shader::spill::is_spilled)) +} + +/// `VICTORY_BVH_QUARANTINE=1`: what the structure builder's stages store +/// stays in the host's copies and is not copied back into title memory. A +/// check for a first run of the whole builder: a stage that stores where +/// it should not can then not reach the title's own objects (run 98), and +/// the programs that walk the structures read the host's copies anyway. +/// shortcut: not a way to run: the title also reads results back (sizes, +/// counters) and gets none, and a copy's pages are overwritten from title +/// memory when the title writes them. +#[cfg(windows)] +pub(crate) fn builder_quarantined(this: This) -> bool { + static ON: OnceLock = OnceLock::new(); + is_builder(this) && *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_QUARANTINE").is_some_and(|v| v == "1")) +} + +/// Whether the title's pipeline `this` is one of the structure builder's. +#[cfg(windows)] +pub(crate) fn is_builder(this: This) -> bool { + !this.is_null() && pipeline(this).builder +} + +/// A stage of the builder was dropped after all: none runs from here on. +#[cfg(windows)] +pub(crate) fn builder_off(why: &'static str) { + let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); + if !b.off { + b.off = true; + tracing::warn!(why, "the ray-tracing structure builder is turned off for the rest of the run: its stages run all or none"); + } +} + +/// At a dispatch of a builder pipeline: whether the builder runs (see +/// [`Builder`]). +#[cfg(windows)] +pub(crate) fn builder_runs() -> bool { + static ALLOWED: OnceLock = OnceLock::new(); + if !*ALLOWED.get_or_init(|| std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1")) { + return false; + } + let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); + if b.off { + return false; + } + if b.whole { + return true; + } + let missing = b.pipelines.iter().filter(|p| !make::now(p)).count(); + if missing > 0 { + b.off = true; + tracing::warn!( + missing, + of = b.pipelines.len(), + "the ray-tracing structure builder stays off: not all of its programs have a host pipeline, and its stages run all or none" + ); + return false; + } + tracing::info!( + pipelines = b.pipelines.len(), + "the ray-tracing structure builder runs: all of its programs have host pipelines" + ); + b.whole = true; + true +} + +/// Whether a console program can store to buffer memory: it has a buffer, +/// typed-buffer, scalar-memory, flat or global store or atomic, or code +/// that is not all known (an instruction of those kinds outside our table, +/// an indirect jump, code that does not decode). Stores to textures +/// (image instructions) and to the program's own scratch memory do not +/// count: neither reaches a buffer's host copy. After upstream #413, +/// which leaves scalar-memory stores out and counts image stores. +#[cfg(windows)] +fn stores(program: &victory_shader::NativeProgram) -> bool { + use victory_shader::gfx10::{Encoding, decode}; + let Ok(code) = decode(&program.code) else { + return true; + }; + code.iter().any(|i| { + let name = i.name(); + match i.encoding { + Encoding::Mubuf + | Encoding::Mtbuf + | Encoding::Smem + | Encoding::Flat + | Encoding::Global => name.is_none_or(|n| { + (n.contains("store") || n.contains("atomic")) && !n.contains("scratch") + }), + Encoding::Sop1 => name.is_none_or(|n| matches!(n, "s_setpc_b64" | "s_swappc_b64")), + _ => false, + } + }) } #[repr(C)] @@ -183,6 +353,9 @@ struct Pipeline { /// (by a worker: the title may release the pipeline meanwhile). #[cfg(windows)] host: Arc, + /// One of the ray-tracing structure builder's ([`Builder`]). + #[cfg(windows)] + builder: bool, } const _: () = assert!(offset_of!(Pipeline, packet) == 0x10); @@ -294,11 +467,9 @@ pub(crate) fn note_drop(this: This) { /// Counts a draw or dispatch dropped for `why` (diagnostics). #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn note_why(why: String) { + crate::capture::op(0, || format!("DROPPED {why}")); let mut drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()); - *drops - .get_or_insert_with(HashMap::new) - .entry(why) - .or_default() += 1; + *drops.get_or_insert_with(HashMap::new).entry(why).or_default() += 1; } /// The drops counted since the last call, most first (diagnostics). @@ -334,11 +505,22 @@ fn hand_out( let host = Arc::new(make::Pending::new(shaders.clone(), graphics)); #[cfg(windows)] make::early(&host); + #[cfg(windows)] + let builder = of_builder(&shaders); + #[cfg(windows)] + if builder { + // Another stage: the group is looked at again at its next dispatch. + let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); + b.pipelines.push(host.clone()); + b.whole = false; + } let pipeline = Box::new(Pipeline { object: Object::new(&FUNCTIONS), packet: [0; 8], #[cfg(windows)] host, + #[cfg(windows)] + builder, shaders, bound: std::sync::atomic::AtomicBool::new(false), }); @@ -513,6 +695,20 @@ mod library; #[cfg(windows)] mod make; +/// Lets the pipeline library's mapped file go from memory when no pipeline +/// has loaded for a while (`library::trim`); called by the host's sweep. +#[cfg(windows)] +pub(crate) fn trim_library() { + library::trim(); +} + +/// The pipeline library's part of the report when the host device is +/// removed (`library::removal_note`). +#[cfg(windows)] +pub(crate) fn library_removal_note() -> String { + library::removal_note() +} + /// Keeps compiled host pipelines, and the list of title pipelines to start /// early, in `dir` (a folder of the cache) across runs. #[cfg(windows)] @@ -591,7 +787,7 @@ mod tests { assert_eq!(slot:: u32>(p, 0x10)(p), 0); } - /// The stream layout Grand Theft Auto VI builds (title+0x86f090): root + /// The stream layout the title builds (title+0x86f090): root /// signature, five shader slots (the first a mesh shader), blend, sample /// mask, rasterizer, depth-stencil 1, sample description, input layout, /// topology, render target and depth formats: 0x2b0 bytes. diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 76166be..aaa2c47 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -8,10 +8,7 @@ use std::ffi::{CStr, CString}; use std::sync::Arc; -use victory_shader::emit::{ - ADDRESS_MAP_SPACE, DESCRIPTOR_WORDS_SPACE, MESH_EMU_SPACE, MeshEmu, ROOT_CBV_SPACE, - SAMPLER_SPACE, USER_DATA_SPACE, unpack_vertex_shader, -}; +use victory_shader::emit::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; @@ -28,8 +25,9 @@ pub(crate) struct GraphicsState { rasterizer: D3D12_RASTERIZER_DESC, depth: D3D12_DEPTH_STENCIL_DESC, depth_bounds: bool, - /// `None` if the stream supplied an invalid input layout. - input_layout: Option, + /// Input elements, their names pointing into `names`. + inputs: Vec, + names: Vec, strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, pub(crate) topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE, pub(crate) targets: D3D12_RT_FORMAT_ARRAY, @@ -37,15 +35,6 @@ pub(crate) struct GraphicsState { samples: DXGI_SAMPLE_DESC, } -impl GraphicsState { - /// Whether this draws depth-tested geometry (the 3D scene), not flat - /// layers (interface, full-screen passes), which keep their own pixel - /// shaders in the debug view. - pub(crate) fn draws_geometry(&self) -> bool { - self.depth_format != DXGI_FORMAT_UNKNOWN && self.depth.DepthEnable.as_bool() - } -} - impl Default for GraphicsState { fn default() -> Self { let target = D3D12_RENDER_TARGET_BLEND_DESC { @@ -88,7 +77,8 @@ impl Default for GraphicsState { ..Default::default() }, depth_bounds: false, - input_layout: Some(InputLayout::default()), + inputs: Vec::new(), + names: Vec::new(), strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED, targets: D3D12_RT_FORMAT_ARRAY::default(), @@ -101,94 +91,28 @@ impl Default for GraphicsState { } } -/// Integer render target formats: D3D12 cannot blend into them. -fn integer_format(f: DXGI_FORMAT) -> bool { - matches!( - f, - DXGI_FORMAT_R32G32B32A32_UINT - | DXGI_FORMAT_R32G32B32A32_SINT - | DXGI_FORMAT_R32G32B32_UINT - | DXGI_FORMAT_R32G32B32_SINT - | DXGI_FORMAT_R16G16B16A16_UINT - | DXGI_FORMAT_R16G16B16A16_SINT - | DXGI_FORMAT_R32G32_UINT - | DXGI_FORMAT_R32G32_SINT - | DXGI_FORMAT_R10G10B10A2_UINT - | DXGI_FORMAT_R8G8B8A8_UINT - | DXGI_FORMAT_R8G8B8A8_SINT - | DXGI_FORMAT_R16G16_UINT - | DXGI_FORMAT_R16G16_SINT - | DXGI_FORMAT_R32_UINT - | DXGI_FORMAT_R32_SINT - | DXGI_FORMAT_R8G8_UINT - | DXGI_FORMAT_R8G8_SINT - | DXGI_FORMAT_R16_UINT - | DXGI_FORMAT_R16_SINT - | DXGI_FORMAT_R8_UINT - | DXGI_FORMAT_R8_SINT - ) -} - -/// The title's blend state as the host takes it: blending off on integer -/// render targets. The console ignores blending there, and titles leave it -/// on (the world sets it on an `R8_UINT` target), but D3D12 does not allow -/// it: vkd3d-proton refuses such a pipeline with `E_INVALIDARG` ("using -/// integer format is not supported"), and its draws are lost. With one -/// description for every target, each target gets its own copy so the -/// others keep theirs. -fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D12_BLEND_DESC { - let count = (targets.NumRenderTargets as usize).min(8); - let per_target = blend.IndependentBlendEnable.as_bool(); - let blends = |i: usize| { - blend.RenderTarget[if per_target { i } else { 0 }] - .BlendEnable - .as_bool() - }; - if !(0..count).any(|i| integer_format(targets.RTFormats[i]) && blends(i)) { - return *blend; - } - let mut host = *blend; - if !per_target { - host.IndependentBlendEnable = true.into(); - host.RenderTarget = [blend.RenderTarget[0]; 8]; - } - for i in 0..count { - if integer_format(targets.RTFormats[i]) { - host.RenderTarget[i].BlendEnable = false.into(); - } - } - host -} - impl GraphicsState { /// Takes in one subobject of a stream: its type, then its data at +4 /// (+8 for those holding pointers). /// /// # Safety - /// `at` points at a whole subobject of type `kind`. When an input layout - /// has a nonzero, in-range count and a non-null, aligned descriptor - /// pointer, that pointer must reference an array of that many initialized - /// elements. Each non-null semantic name read must point to a C string. + /// `at` points at a whole subobject of type `kind`. pub(crate) unsafe fn read(&mut self, kind: u32, at: *const u8) { // SAFETY: the caller passes a whole subobject. unsafe { let data = at.add(4); match kind { - 8 => self.blend = clean_blend(data.cast::().read_unaligned()), + 8 => self.blend = data.cast::().read_unaligned(), 9 => self.sample_mask = data.cast::().read_unaligned(), - 10 => { - self.rasterizer = - clean_rasterizer(data.cast::().read_unaligned()) - } + 10 => self.rasterizer = data.cast::().read_unaligned(), 11 => { - self.depth = - clean_depth(data.cast::().read_unaligned()); + self.depth = data.cast::().read_unaligned(); self.depth_bounds = false; } 21 => { let d = data.cast::().read_unaligned(); self.depth_bounds = d.DepthBoundsTestEnable.as_bool(); - self.depth = clean_depth(D3D12_DEPTH_STENCIL_DESC { + self.depth = D3D12_DEPTH_STENCIL_DESC { DepthEnable: d.DepthEnable, DepthWriteMask: d.DepthWriteMask, DepthFunc: d.DepthFunc, @@ -197,11 +121,32 @@ impl GraphicsState { StencilWriteMask: d.StencilWriteMask, FrontFace: d.FrontFace, BackFace: d.BackFace, - }); + }; } 12 => { let layout = at.add(8).cast::().read_unaligned(); - self.input_layout = InputLayout::read(layout); + if layout.pInputElementDescs.is_null() { + return; + } + let elements = std::slice::from_raw_parts( + layout.pInputElementDescs, + layout.NumElements as usize, + ); + self.names = elements + .iter() + .map(|e| CStr::from_ptr(e.SemanticName.0.cast()).to_owned()) + .collect(); + self.inputs = elements + .iter() + .zip(&self.names) + .map(|(e, name)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(name.as_ptr().cast()), + Format: DXGI_FORMAT( + crate::resource::pc_format(e.Format.0 as u32) as i32 + ), + ..*e + }) + .collect(); } 13 => { self.strip_cut = @@ -212,14 +157,12 @@ impl GraphicsState { D3D12_PRIMITIVE_TOPOLOGY_TYPE(data.cast::().read_unaligned()) } 15 => { - let raw = data.cast::().read_unaligned(); - // SAFETY: plain-old-data D3D12 struct; zeroed to clear padding. - let mut out: D3D12_RT_FORMAT_ARRAY = std::mem::zeroed(); - out.NumRenderTargets = raw.NumRenderTargets; - for (dst, src) in out.RTFormats.iter_mut().zip(raw.RTFormats) { - dst.0 = crate::resource::pc_format(src.0 as u32) as i32; + self.targets = data.cast::().read_unaligned(); + for f in &mut self.targets.RTFormats { + f.0 = crate::resource::target_format(crate::resource::pc_format( + f.0 as u32, + )) as i32; } - self.targets = out; } 16 => { let f = data.cast::().read_unaligned(); @@ -234,15 +177,24 @@ impl GraphicsState { /// Everything the state holds, as text: part of a pipeline's name in /// the library and of the key a title pipeline is started early by. pub(crate) fn describe(&self) -> String { - let inputs = self.input_layout.as_ref().map(InputLayout::describe); - let inputs = inputs.as_deref().unwrap_or(""); + let inputs: Vec = self + .inputs + .iter() + .zip(&self.names) + .map(|(e, name)| { + format!( + "{name:?} {} {} {} {} {} {}", + e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0, e.InstanceDataStepRate + ) + }) + .collect(); let bounds = if self.depth_bounds { " depth-bounds" } else { "" }; format!( - "{:?} {} {:?} {:?}{bounds} {inputs} {} {} {:?} {} {:?}", + "{:?} {} {:?} {:?}{bounds} {inputs:?} {} {} {:?} {} {:?}", self.blend, self.sample_mask, self.rasterizer, @@ -255,8 +207,6 @@ impl GraphicsState { ) } - /// The depth state with the depth bounds test flag a plain description - /// cannot hold: pipelines that enable the test are made from a stream. fn depth1(&self) -> D3D12_DEPTH_STENCIL_DESC1 { let d = &self.depth; D3D12_DEPTH_STENCIL_DESC1 { @@ -271,104 +221,35 @@ impl GraphicsState { DepthBoundsTestEnable: self.depth_bounds.into(), } } -} - -#[derive(Default)] -struct InputLayout { - /// Input elements, their names pointing into `names`. - inputs: Vec, - names: Vec, -} - -impl InputLayout { - /// # Safety - /// The input layout's pointers must meet the requirements of `GraphicsState::read`. - unsafe fn read(layout: D3D12_INPUT_LAYOUT_DESC) -> Option { - let count = layout.NumElements; - if count == 0 { - return Some(Self::default()); - } - let ptr = layout.pInputElementDescs; - if count > D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT - || ptr.is_null() - || !ptr.is_aligned() - { - return None; - } - - let count = count as usize; - // SAFETY: the pointer passed the shape checks and the caller supplies - // the complete array. - let elements = unsafe { std::slice::from_raw_parts(ptr, count) }; - let mut owned = Self { - inputs: Vec::with_capacity(count), - names: Vec::with_capacity(count), - }; - for e in elements { - if e.InputSlot >= D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT || e.SemanticName.is_null() - { - return None; - } - // SAFETY: the caller supplies a C string for each non-null name. - let name = unsafe { CStr::from_ptr(e.SemanticName.0.cast()) }.to_owned(); - owned.inputs.push(D3D12_INPUT_ELEMENT_DESC { - SemanticName: PCSTR(name.as_ptr().cast()), - Format: DXGI_FORMAT(crate::resource::pc_format(e.Format.0 as u32) as i32), - ..*e - }); - owned.names.push(name); - } - Some(owned) - } - - fn describe(&self) -> String { - let inputs: Vec = self - .inputs - .iter() - .zip(&self.names) - .map(|(e, name)| { - format!( - "{name:?} {} {} {} {} {} {}", - e.SemanticIndex, - e.Format.0, - e.InputSlot, - e.AlignedByteOffset, - e.InputSlotClass.0, - e.InstanceDataStepRate, - ) - }) - .collect(); - format!("{inputs:?}") - } /// The vertex buffer slots the input layout reads. fn slots(&self) -> u32 { - self.inputs.iter().fold(0, |m, e| m | 1 << e.InputSlot) + self.inputs + .iter() + .fold(0, |m, e| m | 1 << e.InputSlot.min(31)) } /// The input elements with their byte offsets worked out. - fn elements(&self) -> Option> { - let mut next = [0u32; D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT as usize]; + fn elements(&self) -> Vec { + let mut next = [0u32; 32]; self.inputs .iter() .map(|e| { - let slot = e.InputSlot as usize; + let slot = e.InputSlot.min(31) as usize; let format = e.Format.0 as u32; - let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT { - // The input assembler caps natural element alignment at 4 bytes. - let alignment = bytes.min(4).next_power_of_two(); - next[slot].checked_next_multiple_of(alignment)? + next[slot] } else { e.AlignedByteOffset }; - next[slot] = offset.checked_add(bytes)?; - Some(Input { - slot: e.InputSlot, + let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); + next[slot] = offset + bytes; + Input { + slot: slot as u32, offset, format, per_instance: e.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, - }) + } }) .collect() } @@ -387,6 +268,17 @@ pub(crate) struct Input { const RECTANGLES: i32 = 19; const QUADS: i32 = 32; +/// Whether the title's root SRVs are bound as one-view tables of the +/// buffer's host copy, whose reads past its end return zeros, rather than +/// as root descriptors, which have no size: a mesh shader's vertex fetch +/// has no record limit, and a read past the copy reaches whatever the host +/// placed after it (memory it has freed: the device is removed, upstream +/// PR #493). `VICTORY_ROOT_SRV_DIRECT=1` goes back to root descriptors. +pub(crate) fn bounded_root_srvs() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_ROOT_SRV_DIRECT").is_none()) +} + /// One stage of a host pipeline and where its bindings go. pub(crate) struct Stage { pub(crate) shader: Arc, @@ -395,10 +287,9 @@ pub(crate) struct Stage { /// Root parameters of its root views: (title root parameter, ours). pub(crate) root_cbvs: Vec<(u8, u32)>, pub(crate) root_srvs: Vec<(u8, u32)>, - /// The root parameters of the address map and of the descriptor words, - /// when it reads them. - pub(crate) address_map: Option, - pub(crate) descriptor_words: Option, + /// Root UAVs: one-view tables like the SRVs (or root descriptors with + /// `VICTORY_ROOT_SRV_DIRECT=1`). + pub(crate) root_uavs: Vec<(u8, u32)>, } impl Stage { @@ -409,19 +300,6 @@ impl Stage { } } -/// Additional pipelines and binding slots of a mesh pipeline emulated as -/// compute plus a generated vertex shader. -pub(crate) struct EmulatedMeshPipeline { - pub(crate) emu: MeshEmu, - pub(crate) cs_pso: ID3D12PipelineState, - pub(crate) cs_root: ID3D12RootSignature, - pub(crate) cs_stage: Stage, - pub(crate) cs_uav_param: u32, - pub(crate) cs_cbv_param: Option, - pub(crate) cs_srv_param: Option, - pub(crate) draw_srv_param: u32, -} - pub(crate) struct HostPipeline { /// A compute pipeline (else graphics). pub(crate) compute: bool, @@ -429,176 +307,21 @@ pub(crate) struct HostPipeline { pub(crate) mesh: bool, pub(crate) pso: ID3D12PipelineState, pub(crate) root: ID3D12RootSignature, - /// Vertex, then pixel stage, or the compute stage. For an emulated - /// mesh pipeline this holds only the pixel stage; the mesh compute - /// stage lives in `mesh_emu`. + /// Vertex, then pixel stage, or the compute stage. pub(crate) stages: Vec, - /// Compute and unpack-vertex pipeline state for emulated mesh shaders. - pub(crate) mesh_emu: Option, /// The vertex buffer slots it reads (bit per slot). pub(crate) slots: u32, pub(crate) inputs: Vec, + /// Has the geometry stage that completes the console's rectangles + /// (`victory_shader::emit::rect_list_gs`): its rectangle draws go out + /// as the title gives them, three vertices a rectangle. + pub(crate) rects: bool, /// Its shaders, for reports of slow submissions. pub(crate) name: String, -} - -/// `VICTORY_DEBUG_PS=1`: graphics pipelines that draw depth-tested -/// geometry draw with our debug pixel shader ([`victory_shader::emit::debug_ps`]), surfaces coloured by their -/// slope, instead of the title's: the geometry of every draw whose vertex -/// or mesh stage translates, lit or not, its pixel shader translated or not. -pub(crate) fn debug_ps() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - let on = std::env::var_os("VICTORY_DEBUG_PS").is_some(); - if on { - tracing::info!( - "graphics pipelines draw with the debug pixel shader (VICTORY_DEBUG_PS)" - ); - } - on - }) -} - -/// Whether geometry whose pixel shader does not translate (or is refused) -/// is drawn with the debug pixel shader instead of dropped: on unless -/// `VICTORY_PS_FALLBACK=0`. -fn ps_fallback() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("VICTORY_PS_FALLBACK").map_or(true, |v| v != "0")) -} - -// The boxes keep each range's address stable while later ranges are pushed; -// root signature serialization reads through those raw pointers. -#[allow(clippy::vec_box)] -fn push_stage_params( - shader: &Arc, - visibility: D3D12_SHADER_VISIBILITY, - params: &mut Vec, - ranges: &mut Vec>, - samplers: &mut Vec, -) -> Option { - let t = &shader.translated()?.host; - let mut stage = Stage { - shader: shader.clone(), - user_data: None, - root_cbvs: Vec::new(), - root_srvs: Vec::new(), - address_map: None, - descriptor_words: None, - }; - let dwords = t.user_data_dwords(); - if dwords > 0 { - stage.user_data = Some((params.len() as u32, dwords)); - params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Constants: D3D12_ROOT_CONSTANTS { - ShaderRegister: 0, - RegisterSpace: USER_DATA_SPACE, - Num32BitValues: dwords, - }, - }, - ShaderVisibility: visibility, - }); - } - for (slots, kind, out) in [ - ( - &t.root_cbvs, - D3D12_ROOT_PARAMETER_TYPE_CBV, - &mut stage.root_cbvs, - ), - ( - &t.root_srvs, - D3D12_ROOT_PARAMETER_TYPE_SRV, - &mut stage.root_srvs, - ), - ] { - for &slot in slots { - out.push((slot, params.len() as u32)); - // A root SRV is a raw address the GPU reads without - // bounds: the console's reads past the title buffer - // land in other title memory, ours past its host copy - // in unmapped memory (a GPU page fault and a lost - // device in the world). A table of one raw view sized - // to the copy reads zeros there instead; the shader's - // binding (`t`, a ByteAddressBuffer) is the same. - if kind == D3D12_ROOT_PARAMETER_TYPE_SRV { - ranges.push(Box::new(D3D12_DESCRIPTOR_RANGE1 { - RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, - NumDescriptors: 1, - BaseShaderRegister: u32::from(slot), - RegisterSpace: ROOT_CBV_SPACE, - Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE - | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, - OffsetInDescriptorsFromTableStart: 0, - })); - let range: &D3D12_DESCRIPTOR_RANGE1 = ranges.last().expect("just pushed"); - params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 { - NumDescriptorRanges: 1, - pDescriptorRanges: range, - }, - }, - ShaderVisibility: visibility, - }); - continue; - } - params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: kind, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR1 { - ShaderRegister: u32::from(slot), - RegisterSpace: ROOT_CBV_SPACE, - Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, - }, - }, - ShaderVisibility: visibility, - }); - } - } - for (wanted, space, out) in [ - (t.address_map, ADDRESS_MAP_SPACE, &mut stage.address_map), - ( - t.descriptor_words, - DESCRIPTOR_WORDS_SPACE, - &mut stage.descriptor_words, - ), - ] { - if wanted { - *out = Some(params.len() as u32); - params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR1 { - ShaderRegister: 0, - RegisterSpace: space, - Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, - }, - }, - ShaderVisibility: visibility, - }); - } - } - for (n, s) in t.static_samplers.iter().enumerate() { - samplers.push(D3D12_STATIC_SAMPLER_DESC { - Filter: D3D12_FILTER(s.filter as i32), - AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32), - AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32), - AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32), - MipLODBias: s.mip_lod_bias, - MaxAnisotropy: s.max_anisotropy, - ComparisonFunc: D3D12_COMPARISON_FUNC(s.comparison as i32), - BorderColor: D3D12_STATIC_BORDER_COLOR(s.border as i32), - MinLOD: s.min_lod, - MaxLOD: s.max_lod, - ShaderRegister: n as u32, - RegisterSpace: SAMPLER_SPACE, - ShaderVisibility: visibility, - }); - } - Some(stage) + /// Its depth, stencil, cull and blend state in short, for the frame + /// listing (empty for compute). + #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] + pub(crate) state: String, } /// Logs a pipeline that gets no host pipeline, once per reason. @@ -614,41 +337,11 @@ fn refuse(reason: &'static str, shaders: &[Arc]) -> Option impl HostPipeline { /// A host pipeline for vertex and pixel shaders with the graphics - /// state `g`, or for one compute shader. A pipeline drawing depth-tested - /// geometry falls back to our debug pixel shader where the title's does - /// not translate or the host refuses it (and, in the debug view, to the - /// title's where ours is refused), so its geometry is drawn rather than - /// dropped (`VICTORY_PS_FALLBACK=0` turns that off). + /// state `g`, or for one compute shader. pub(crate) fn new(shaders: &[Arc], g: Option<&GraphicsState>) -> Option { - let geometry = g.is_some_and(GraphicsState::draws_geometry) - && shaders.iter().any(|s| s.stage == "pixel"); - if !geometry { - return Self::make(shaders, g, false); - } - let first = debug_ps(); - if let Some(p) = Self::make(shaders, g, first) { - return Some(p); - } - if !first && !ps_fallback() { - return None; - } - let p = Self::make(shaders, g, !first)?; - if !first { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::info!("pixel shaders that do not translate are replaced by the debug one") - }); - } - Some(p) - } - - /// [`HostPipeline::new`] with our debug pixel shader (`debug`) or the - /// title's. - fn make( - shaders: &[Arc], - g: Option<&GraphicsState>, - debug: bool, - ) -> Option { + // For the report when the host device is removed: what this thread + // has in the library from here on. + super::library::label(format!("{shaders:?}")); let find = |stage| shaders.iter().find(|s| s.stage == stage); let compute = match shaders { [cs] if cs.stage == "compute" => Some(cs), @@ -674,87 +367,149 @@ impl HostPipeline { (None, None) => return refuse("no vertex or mesh shader", shaders), }; let mut stages = vec![first]; - // Debug view: the title's pixel shader is left out (it need not - // translate) and ours stands in at the pixel slot. - if !debug { - stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL))); - } + stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL))); stages }; - let host = host()?; - if mesh.is_some() && !(host.mesh_shaders() || host.emulate_mesh_shaders()) { - return refuse( - "the host GPU has no mesh shaders (or no shader model 6.6)", - shaders, - ); + if mesh.is_some() && !host()?.mesh_shaders() { + return refuse("the host GPU has no mesh shaders (or no shader model 6.6)", shaders); } for (s, _) in &stages { s.translated()?; } - // The debug view's pixel shader, one output per colour target. - let debug_ps_shader = (compute.is_none() && debug) - .then(|| victory_shader::emit::debug_ps(g.map_or(1, |g| g.targets.NumRenderTargets))); - if let Some(ms) = mesh { - let ms_translated = ms.translated()?; - if let Some(emu) = ms_translated.host.mesh_emu.as_ref() { - let Some(g) = g else { - return refuse("graphics state not kept (plain description)", shaders); - }; - return emulated_mesh_pipeline( - ms, - if debug { None } else { find("pixel") }, - emu, - g, - shaders, - debug_ps_shader.as_ref(), - ); - } - if !host.mesh_shaders() { - return refuse( - "the host GPU has no mesh shaders (or no shader model 6.6)", - shaders, - ); - } - } + let host = host()?; // The root signature the translated shaders' bindings define. let mut params: Vec = Vec::new(); - // Root SRVs are bound as one-view tables (see below); their ranges - // must outlive the serialisation, so each is boxed here. + // The ranges table parameters point at, alive until the root + // signature is made. let mut ranges: Vec> = Vec::new(); let mut samplers = Vec::new(); let mut bound = Vec::new(); for &(shader, visibility) in &stages { - bound.push(push_stage_params( - shader, - visibility, - &mut params, - &mut ranges, - &mut samplers, - )?); - } - let (root, root_blob) = - match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { - Ok(root) => root, - Err(e) => { - tracing::warn!(error = %e, ?shaders, "host root signature refused"); - return None; - } + let t = &shader.translated()?.host; + let mut stage = Stage { + shader: shader.clone(), + user_data: None, + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), }; - for (s, _) in &stages { - if crate::breadcrumb::enabled() { - crate::breadcrumb::note_stage(&s.container, &format!("{shaders:?}")); + let dwords = t.user_data_dwords(); + if dwords > 0 { + stage.user_data = Some((params.len() as u32, dwords)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: USER_DATA_SPACE, + Num32BitValues: dwords, + }, + }, + ShaderVisibility: visibility, + }); } + for (slots, kind, out) in [ + ( + &t.root_cbvs, + D3D12_ROOT_PARAMETER_TYPE_CBV, + &mut stage.root_cbvs, + ), + ( + &t.root_srvs, + D3D12_ROOT_PARAMETER_TYPE_SRV, + &mut stage.root_srvs, + ), + ( + &t.root_uavs, + D3D12_ROOT_PARAMETER_TYPE_UAV, + &mut stage.root_uavs, + ), + ] { + for &slot in slots { + let uav = kind == D3D12_ROOT_PARAMETER_TYPE_UAV; + // Ours, not the title's, stay root descriptors: the + // table of strides, the directory of title memory by + // address and its fault notes. + let ours = if uav { + slot == victory_shader::emit::SLOT_FAULTS + } else { + slot == victory_shader::emit::SLOT_STRIDES + || slot == victory_shader::emit::SLOT_MEMORY + }; + if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { + // A one-view table: the view's size bounds the + // reads (and a root UAV's writes), which a root + // descriptor leaves unbounded. + // (Our own table of strides stays a descriptor.) + ranges.push(Box::new(D3D12_DESCRIPTOR_RANGE1 { + RangeType: if uav { + D3D12_DESCRIPTOR_RANGE_TYPE_UAV + } else { + D3D12_DESCRIPTOR_RANGE_TYPE_SRV + }, + NumDescriptors: 1, + BaseShaderRegister: u32::from(slot), + RegisterSpace: ROOT_CBV_SPACE, + Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE + | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, + OffsetInDescriptorsFromTableStart: 0, + })); + let range: *const D3D12_DESCRIPTOR_RANGE1 = &**ranges.last()?; + out.push((slot, params.len() as u32)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 { + NumDescriptorRanges: 1, + pDescriptorRanges: range, + }, + }, + ShaderVisibility: visibility, + }); + continue; + } + out.push((slot, params.len() as u32)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: kind, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: u32::from(slot), + RegisterSpace: ROOT_CBV_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: visibility, + }); + } + } + for (n, s) in t.static_samplers.iter().enumerate() { + samplers.push(D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER(s.filter as i32), + AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32), + AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32), + AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32), + MipLODBias: s.mip_lod_bias, + MaxAnisotropy: s.max_anisotropy, + ComparisonFunc: D3D12_COMPARISON_FUNC(s.comparison as i32), + BorderColor: D3D12_STATIC_BORDER_COLOR(s.border as i32), + MinLOD: s.min_lod, + MaxLOD: s.max_lod, + ShaderRegister: n as u32, + RegisterSpace: SAMPLER_SPACE, + ShaderVisibility: visibility, + }); + } + bound.push(stage); } - let code = |i: usize| { - if i == 1 - && let Some(d) = &debug_ps_shader - { - return D3D12_SHADER_BYTECODE { - pShaderBytecode: d.dxil.as_ptr().cast(), - BytecodeLength: d.dxil.len(), - }; + let (root, root_blob) = match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { + Ok(root) => root, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host root signature refused"); + return None; } + }; + let code = |i: usize| { stages.get(i).and_then(|(s, _)| s.translated()).map_or( D3D12_SHADER_BYTECODE::default(), |t| D3D12_SHADER_BYTECODE { @@ -794,10 +549,11 @@ impl HostPipeline { pso, root, stages: bound, - mesh_emu: None, name: format!("{shaders:?}"), slots: 0, inputs: Vec::new(), + rects: false, + state: String::new(), }); } let Some(g) = g else { @@ -820,21 +576,17 @@ impl HostPipeline { }; let state = g.describe(); if mesh.is_some() { + // "triangles": the stream names its topology since it did not + // load from the library without one (see `mesh_pipeline`); a + // new name keeps such entries, stored before, from being + // looked up again. let name = super::library::name( - "mesh", + "mesh triangles", &root_blob, &[&code_bytes(&code(0)), &code_bytes(&code(1))], &state, ); - let pso = match mesh_pipeline( - &host.device, - &root, - code(0), - code(1), - g, - depth_bounds, - &name, - ) { + let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g, depth_bounds, &name) { Ok(pso) => pso, Err(e) => { tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused"); @@ -850,31 +602,45 @@ impl HostPipeline { pso, root, stages: bound, - mesh_emu: None, name: format!("{shaders:?}"), slots: 0, inputs: Vec::new(), + rects: false, + state: String::new(), }); } - let Some(layout) = &g.input_layout else { - return refuse("invalid input layout", shaders); - }; - let Some(inputs) = layout.elements() else { - return refuse("input layout byte offset overflow", shaders); - }; - let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // A pipeline the title makes for rectangles gets a geometry stage + // that completes each one from the three vertices the vertex + // shader made. Without it (refused here or by the host) the draws + // fall back on what `draw` does for rectangles. + let mut rect_gs = None; + if g.topology.0 == RECTANGLES { + let ps = stages.get(1).and_then(|(s, _)| s.translated()); + let vs = &stages[0].0.translated()?.host.dxil; + match victory_shader::emit::rect_list_gs(vs, ps.map(|t| &t.host.dxil[..])) { + Ok(gs) => rect_gs = Some(gs), + Err(e) => tracing::warn!(error = %e, ?shaders, "no rectangle geometry stage"), + } + } + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { // SAFETY: a borrowed pointer the description never releases. pRootSignature: unsafe { std::mem::transmute_copy(&root) }, VS: code(0), PS: code(1), - BlendState: host_blend(&g.blend, &g.targets), + GS: rect_gs.as_ref().map_or(D3D12_SHADER_BYTECODE::default(), |gs| { + D3D12_SHADER_BYTECODE { + pShaderBytecode: gs.as_ptr().cast(), + BytecodeLength: gs.len(), + } + }), + BlendState: g.blend, SampleMask: g.sample_mask, RasterizerState: g.rasterizer, DepthStencilState: g.depth, InputLayout: D3D12_INPUT_LAYOUT_DESC { - pInputElementDescs: layout.inputs.as_ptr(), - NumElements: layout.inputs.len() as u32, + pInputElementDescs: g.inputs.as_ptr(), + NumElements: g.inputs.len() as u32, }, IBStripCutValue: g.strip_cut, // The console's rectangle and quad types draw as triangles on @@ -889,23 +655,43 @@ impl HostPipeline { SampleDesc: g.samples, ..Default::default() }; - let name = super::library::name( - "graphics", - &root_blob, - &[&code_bytes(&code(0)), &code_bytes(&code(1))], - &state, - ); - let made = if depth_bounds { - graphics_depth_bounds_pipeline(&host.device, &root, &desc, g.depth1(), &name) - } else { + // A pipeline with the geometry stage has a name of its own in the + // library; the others keep theirs. + let name = |gs: Option<&Vec>| match gs { + Some(gs) => super::library::name( + "graphics rectangles", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1)), &gs[..]], + &state, + ), + None => super::library::name( + "graphics", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1))], + &state, + ), + }; + let make = |desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, name: &str| { + if depth_bounds { + return graphics_depth_bounds_pipeline(&host.device, &root, desc, g.depth1(), name); + } super::library::pipeline( - &name, + name, // SAFETY: the description points at live data. - |library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) }, + |library, name| unsafe { library.LoadGraphicsPipeline(name, desc) }, // SAFETY: as above. - || unsafe { host.device.CreateGraphicsPipelineState(&desc) }, + || unsafe { host.device.CreateGraphicsPipelineState(desc) }, ) }; + let mut made = make(&desc, &name(rect_gs.as_ref())); + if made.is_err() && rect_gs.is_some() { + // The host refused the geometry stage: once more without it. + tracing::warn!(?shaders, "host pipeline refused with the rectangle geometry stage"); + host.log_messages(); + desc.GS = D3D12_SHADER_BYTECODE::default(); + rect_gs = None; + made = make(&desc, &name(None)); + } let pso = match made { Ok(pso) => pso, Err(e) => { @@ -919,6 +705,7 @@ impl HostPipeline { tracing::debug!( ?shaders, depth = ?g.depth, + depth_bounds, dsv = g.depth_format.0, targets = ?&g.targets.RTFormats[..g.targets.NumRenderTargets.min(8) as usize], blend = ?g.blend.RenderTarget[0], @@ -931,251 +718,46 @@ impl HostPipeline { pso, root, stages: bound, - mesh_emu: None, name: format!("{shaders:?}"), - slots: layout.slots(), - inputs, - }) - } -} - -/// A mesh pipeline emulated as compute plus a generated vertex shader. -/// The compute step writes the mesh records into the shared emulation -/// buffer; the graphics step unpacks them with no input assembler data. -fn emulated_mesh_pipeline( - ms: &Arc, - ps: Option<&Arc>, - emu: &MeshEmu, - g: &GraphicsState, - shaders: &[Arc], - debug_ps: Option<&victory_shader::emit::HostShader>, -) -> Option { - let host = host()?; - let mut cs_params = Vec::new(); - let mut cs_ranges = Vec::new(); - let mut cs_samplers = Vec::new(); - let cs_stage = push_stage_params( - ms, - D3D12_SHADER_VISIBILITY_ALL, - &mut cs_params, - &mut cs_ranges, - &mut cs_samplers, - )?; - let cs_uav_param = cs_params.len() as u32; - cs_params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR1 { - ShaderRegister: 0, - RegisterSpace: MESH_EMU_SPACE, - Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }); - let (cs_cbv_param, cs_srv_param) = if emu.reads_group_id { - let cbv = cs_params.len() as u32; - cs_params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Constants: D3D12_ROOT_CONSTANTS { - ShaderRegister: 0, - RegisterSpace: MESH_EMU_SPACE, - Num32BitValues: 4, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }); - let srv = cs_params.len() as u32; - cs_params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR1 { - ShaderRegister: 0, - RegisterSpace: MESH_EMU_SPACE, - Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, - }, + slots: g.slots(), + inputs: g.elements(), + rects: rect_gs.is_some(), + state: { + let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]); + let face = |f: &D3D12_DEPTH_STENCILOP_DESC| { + format!( + "fail {} depth-fail {} pass {} func {}", + f.StencilFailOp.0, f.StencilDepthFailOp.0, f.StencilPassOp.0, f.StencilFunc.0 + ) + }; + let bounds = if depth_bounds { " bounds true" } else { "" }; + format!( + "depth {} write {} func {}{bounds}; stencil {} read {:#x} write {:#x} front [{}] back [{}]; cull {} front-ccw {}; blend {} src {} dst {} op {} mask {:#x}", + d.DepthEnable.as_bool(), + d.DepthWriteMask.0, + d.DepthFunc.0, + d.StencilEnable.as_bool(), + d.StencilReadMask, + d.StencilWriteMask, + face(&d.FrontFace), + face(&d.BackFace), + r.CullMode.0, + r.FrontCounterClockwise.as_bool(), + b.BlendEnable.as_bool(), + b.SrcBlend.0, + b.DestBlend.0, + b.BlendOp.0, + b.RenderTargetWriteMask + ) }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }); - (Some(cbv), Some(srv)) - } else { - (None, None) - }; - let (cs_root, cs_root_blob) = match root_signature(&host.device, &cs_params, &cs_samplers, true) - { - Ok(root) => root, - Err(e) => { - tracing::warn!(error = %e, ?shaders, "emulated mesh CS root signature refused"); - return None; - } - }; - let cs_dxil = &ms.translated()?.host.dxil; - let cs_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { - // SAFETY: borrowed root signature pointer for the Create/Load call. - pRootSignature: unsafe { std::mem::transmute_copy(&cs_root) }, - CS: D3D12_SHADER_BYTECODE { - pShaderBytecode: cs_dxil.as_ptr().cast(), - BytecodeLength: cs_dxil.len(), - }, - ..Default::default() - }; - let cs_name = super::library::name("mesh-emu-cs", &cs_root_blob, &[cs_dxil], ""); - let cs_pso = match super::library::pipeline( - &cs_name, - // SAFETY: descriptor points at live root signature and CS DXIL bytes. - |library, name| unsafe { library.LoadComputePipeline(name, &cs_desc) }, - // SAFETY: as above. - || unsafe { host.device.CreateComputePipelineState(&cs_desc) }, - ) { - Ok(pso) => pso, - Err(e) => { - tracing::warn!(error = %e, ?shaders, "emulated mesh CS pipeline refused"); - host.log_messages(); - return None; - } - }; - crate::host::name(&cs_pso, || format!("{shaders:?} [mesh-emu cs]")); - - let title_ps_dxil = match ps { - Some(ps) => Some(ps.translated()?.host.dxil.as_slice()), - None => None, - }; - let ps_dxil = debug_ps.map(|d| d.dxil.as_slice()).or(title_ps_dxil); - let unpack_vs = match unpack_vertex_shader(emu, ps_dxil) { - Ok(vs) => vs, - Err(e) => { - tracing::warn!(error = %e, ?shaders, "unpack vertex shader generation failed"); - return None; - } - }; - let mut gfx_params = Vec::new(); - let mut gfx_ranges = Vec::new(); - let mut gfx_samplers = Vec::new(); - let mut gfx_stages = Vec::new(); - if let Some(ps) = ps { - gfx_stages.push(push_stage_params( - ps, - D3D12_SHADER_VISIBILITY_PIXEL, - &mut gfx_params, - &mut gfx_ranges, - &mut gfx_samplers, - )?); + }) } - let draw_srv_param = gfx_params.len() as u32; - gfx_params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR1 { - ShaderRegister: 0, - RegisterSpace: MESH_EMU_SPACE, - Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_VERTEX, - }); - let (gfx_root, gfx_root_blob) = match root_signature( - &host.device, - &gfx_params, - &gfx_samplers, - false, - ) { - Ok(root) => root, - Err(e) => { - tracing::warn!(error = %e, ?shaders, "emulated mesh graphics root signature refused"); - return None; - } - }; - let ps_code = ps_dxil.map_or_else(D3D12_SHADER_BYTECODE::default, |b| D3D12_SHADER_BYTECODE { - pShaderBytecode: b.as_ptr().cast(), - BytecodeLength: b.len(), - }); - let gfx_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { - // SAFETY: borrowed root signature pointer for the Create/Load call. - pRootSignature: unsafe { std::mem::transmute_copy(&gfx_root) }, - VS: D3D12_SHADER_BYTECODE { - pShaderBytecode: unpack_vs.as_ptr().cast(), - BytecodeLength: unpack_vs.len(), - }, - PS: ps_code, - BlendState: host_blend(&g.blend, &g.targets), - SampleMask: g.sample_mask, - RasterizerState: g.rasterizer, - DepthStencilState: g.depth, - InputLayout: D3D12_INPUT_LAYOUT_DESC { - pInputElementDescs: std::ptr::null(), - NumElements: 0, - }, - IBStripCutValue: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, - PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, - NumRenderTargets: g.targets.NumRenderTargets, - RTVFormats: g.targets.RTFormats, - DSVFormat: g.depth_format, - SampleDesc: g.samples, - ..Default::default() - }; - let depth_bounds = if g.depth_bounds { - host.depth_bounds() - } else { - false - }; - let state = g.describe(); - let gfx_name = super::library::name( - "mesh-emu-gfx", - &gfx_root_blob, - &[&unpack_vs, ps_dxil.unwrap_or(&[])], - &state, - ); - let made = if depth_bounds { - graphics_depth_bounds_pipeline(&host.device, &gfx_root, &gfx_desc, g.depth1(), &gfx_name) - } else { - super::library::pipeline( - &gfx_name, - // SAFETY: descriptor points at live root signature, VS, and PS bytes. - |library, name| unsafe { library.LoadGraphicsPipeline(name, &gfx_desc) }, - // SAFETY: as above. - || unsafe { host.device.CreateGraphicsPipelineState(&gfx_desc) }, - ) - }; - let gfx_pso = match made { - Ok(pso) => pso, - Err(e) => { - tracing::warn!(error = %e, ?shaders, "emulated mesh graphics pipeline refused"); - host.log_messages(); - return None; - } - }; - crate::host::name(&gfx_pso, || format!("{shaders:?} [mesh-emu gfx]")); - tracing::info!(?shaders, "host emulated mesh pipeline"); - Some(HostPipeline { - compute: false, - mesh: true, - pso: gfx_pso, - root: gfx_root, - stages: gfx_stages, - mesh_emu: Some(EmulatedMeshPipeline { - emu: emu.clone(), - cs_pso, - cs_root, - cs_stage, - cs_uav_param, - cs_cbv_param, - cs_srv_param, - draw_srv_param, - }), - slots: 0, - inputs: Vec::new(), - name: format!("{shaders:?}"), - }) } -/// A mesh pipeline from the title's graphics state: the pipeline-state /// A stream subobject: its type, then its description, pointer-aligned. #[repr(C, align(8))] struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); -/// A pipeline made from a stream of subobjects, stored in the library -/// under `name` as any other. fn stream_pipeline( device: &ID3D12Device, stream: &mut S, @@ -1196,9 +778,9 @@ fn stream_pipeline( ) } -/// A graphics pipeline with the depth bounds test enabled: the plain -/// description has nowhere for the flag, so the pipeline is made from a -/// stream with a DEPTH_STENCIL1 subobject. +/// A graphics pipeline enabling the depth bounds test: `D3D12_GRAPHICS_PIPELINE_STATE_DESC` +/// has no field for `DepthBoundsTestEnable`, so it is created and loaded as a +/// pipeline-state stream with `DEPTH_STENCIL1`. fn graphics_depth_bounds_pipeline( device: &ID3D12Device, root: &ID3D12RootSignature, @@ -1232,49 +814,21 @@ fn graphics_depth_bounds_pipeline( RTFormats: d.RTVFormats, NumRenderTargets: d.NumRenderTargets, }; - // SAFETY: plain-old-data subobjects; the zeroed base clears padding so - // the library's description comparison is deterministic. - let mut base: Stream = unsafe { std::mem::zeroed() }; - base.root = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, - root.as_raw(), - ); - base.vs = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, d.VS); - base.ps = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, d.PS); - base.blend = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, d.BlendState); - base.mask = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, - d.SampleMask, - ); - base.raster = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, - d.RasterizerState, - ); - base.depth = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, depth); - base.input = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, - d.InputLayout, - ); - base.strip_cut = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, - d.IBStripCutValue, - ); - base.topology = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, - d.PrimitiveTopologyType, - ); - base.targets = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, - targets, - ); - base.dsv = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, - d.DSVFormat, - ); - base.samples = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, - d.SampleDesc, - ); + let base = Stream { + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + vs: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, d.VS), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, d.PS), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, d.BlendState), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, d.SampleMask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, d.RasterizerState), + depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, depth), + input: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, d.InputLayout), + strip_cut: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, d.IBStripCutValue), + topology: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, d.PrimitiveTopologyType), + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, d.DSVFormat), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, d.SampleDesc), + }; if d.GS.pShaderBytecode.is_null() { let mut stream = base; stream_pipeline(device, &mut stream, name) @@ -1287,7 +841,17 @@ fn graphics_depth_bounds_pipeline( } } -/// stream form (no input layout or topology). +/// A mesh pipeline from the title's graphics state: the pipeline-state +/// stream form (no input layout). +/// +/// The stream names a triangle topology, which D3D12 does not need for a +/// mesh shader: without it the pipeline library refuses to load a stored +/// pipeline with the very stream it was made from (`E_INVALIDARG`; debug +/// layer message 972, "does not match the one used to create the PSO"), so +/// every mesh pipeline was compiled again, and its store then refused (970, +/// "already exists"). The translation makes triangle mesh shaders only +/// (`mesh_prologue` refuses others), and the debug layer wants the two to +/// agree (1323). fn mesh_pipeline( device: &ID3D12Device, root: &ID3D12RootSignature, @@ -1297,94 +861,70 @@ fn mesh_pipeline( depth_bounds: bool, name: &str, ) -> windows::core::Result { + use windows::core::Interface; + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + ms: Sub, + ps: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + topology: Sub, + } + let build = |depth: Sub<_>| { + let mut stream = Stream { + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), + depth, + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), + topology: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + ), + }; + stream_pipeline(device, &mut stream, name) + }; if depth_bounds { - let mut stream = mesh_stream( - root, - ms, - ps, - g, - Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, - g.depth1(), + let mut stream = Stream { + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), + depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, g.depth1()), + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), + topology: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, ), - ); + }; stream_pipeline(device, &mut stream, name) } else { - let mut stream = mesh_stream( - root, - ms, - ps, - g, - Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth), - ); - stream_pipeline(device, &mut stream, name) + build(Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth)) } } -#[repr(C)] -struct MeshStream { - root: Sub<*mut std::ffi::c_void>, - ms: Sub, - ps: Sub, - blend: Sub, - mask: Sub, - raster: Sub, - depth: Sub, - targets: Sub, - dsv: Sub, - samples: Sub, -} - -/// The mesh pipeline's subobject stream, generic over the depth -/// description: DEPTH_STENCIL1 when the pipeline enables the depth bounds -/// test, the plain one otherwise. -fn mesh_stream( - root: &ID3D12RootSignature, - ms: D3D12_SHADER_BYTECODE, - ps: D3D12_SHADER_BYTECODE, - g: &GraphicsState, - depth: Sub, -) -> MeshStream { - use windows::core::Interface; - // SAFETY: `MeshStream` is plain-old-data; zeroing clears padding inside - // `Sub` so D3D12's pipeline library desc comparison is deterministic. - let mut stream: MeshStream = unsafe { std::mem::zeroed() }; - stream.root = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, - root.as_raw(), - ); - stream.ms = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms); - stream.ps = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps); - stream.blend = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, - host_blend(&g.blend, &g.targets), - ); - stream.mask = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, - g.sample_mask, - ); - stream.raster = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer); - stream.depth = depth; - stream.targets = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, - g.targets, - ); - stream.dsv = Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, - g.depth_format, - ); - stream.samples = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples); - stream -} - /// The bytes of shader code (none for an absent stage). fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec { if code.pShaderBytecode.is_null() { return Vec::new(); } // SAFETY: a translation's own bytes, alive while its shader is. - unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::(), code.BytecodeLength) } - .to_vec() + unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::(), code.BytecodeLength) }.to_vec() } fn root_signature( @@ -1434,644 +974,351 @@ fn root_signature( } } -/// Copies a blend description field-by-field into zeroed memory so -/// uninitialized padding bytes from the title's stream cannot cause -/// `ID3D12PipelineLibrary` description mismatches. -fn clean_blend(b: D3D12_BLEND_DESC) -> D3D12_BLEND_DESC { - // SAFETY: plain-old-data D3D12 struct; zeroed to clear padding. - let mut out: D3D12_BLEND_DESC = unsafe { std::mem::zeroed() }; - out.AlphaToCoverageEnable = b.AlphaToCoverageEnable; - out.IndependentBlendEnable = b.IndependentBlendEnable; - for (dst, src) in out.RenderTarget.iter_mut().zip(b.RenderTarget) { - // SAFETY: plain-old-data D3D12 struct; zeroed to clear padding. - let mut rt: D3D12_RENDER_TARGET_BLEND_DESC = unsafe { std::mem::zeroed() }; - rt.BlendEnable = src.BlendEnable; - rt.LogicOpEnable = src.LogicOpEnable; - rt.SrcBlend = src.SrcBlend; - rt.DestBlend = src.DestBlend; - rt.BlendOp = src.BlendOp; - rt.SrcBlendAlpha = src.SrcBlendAlpha; - rt.DestBlendAlpha = src.DestBlendAlpha; - rt.BlendOpAlpha = src.BlendOpAlpha; - rt.LogicOp = src.LogicOp; - rt.RenderTargetWriteMask = src.RenderTargetWriteMask; - *dst = rt; - } - out -} - -/// Copies a rasterizer description field-by-field into zeroed memory. -fn clean_rasterizer(r: D3D12_RASTERIZER_DESC) -> D3D12_RASTERIZER_DESC { - // SAFETY: plain-old-data D3D12 struct; zeroed to clear padding. - let mut out: D3D12_RASTERIZER_DESC = unsafe { std::mem::zeroed() }; - out.FillMode = r.FillMode; - out.CullMode = r.CullMode; - out.FrontCounterClockwise = r.FrontCounterClockwise; - out.DepthBias = r.DepthBias; - out.DepthBiasClamp = r.DepthBiasClamp; - out.SlopeScaledDepthBias = r.SlopeScaledDepthBias; - out.DepthClipEnable = r.DepthClipEnable; - out.MultisampleEnable = r.MultisampleEnable; - out.AntialiasedLineEnable = r.AntialiasedLineEnable; - out.ForcedSampleCount = r.ForcedSampleCount; - out.ConservativeRaster = r.ConservativeRaster; - out -} - -/// Copies a depth-stencil description field-by-field into zeroed memory. -fn clean_depth(d: D3D12_DEPTH_STENCIL_DESC) -> D3D12_DEPTH_STENCIL_DESC { - // SAFETY: plain-old-data D3D12 struct; zeroed to clear padding. - let mut out: D3D12_DEPTH_STENCIL_DESC = unsafe { std::mem::zeroed() }; - out.DepthEnable = d.DepthEnable; - out.DepthWriteMask = d.DepthWriteMask; - out.DepthFunc = d.DepthFunc; - out.StencilEnable = d.StencilEnable; - out.StencilReadMask = d.StencilReadMask; - out.StencilWriteMask = d.StencilWriteMask; - out.FrontFace = d.FrontFace; - out.BackFace = d.BackFace; - out -} - #[cfg(test)] mod tests { + use std::path::{Path, PathBuf}; + use std::sync::atomic::Ordering; + use super::*; - fn targets(formats: &[DXGI_FORMAT]) -> D3D12_RT_FORMAT_ARRAY { - let mut t = D3D12_RT_FORMAT_ARRAY { - NumRenderTargets: formats.len() as u32, - ..Default::default() + /// A triangle mesh shader of our own and a pixel shader for it. + const MS: &str = "struct V { float4 p : SV_Position; }; + [outputtopology(\"triangle\")] [numthreads(1, 1, 1)] + void main(out vertices V v[3], out indices uint3 t[1]) { + SetMeshOutputCounts(3, 1); + v[0].p = float4(0, 0, 0, 1); + v[1].p = float4(1, 0, 0, 1); + v[2].p = float4(0, 1, 0, 1); + t[0] = uint3(0, 1, 2); + }"; + const PS: &str = "float4 main() : SV_Target { return 1; }"; + + /// The PC `dxc.exe` (`VICTORY_PC_DXC`, else the newest Windows SDK's). + fn dxc() -> Option { + let dxc = match std::env::var_os("VICTORY_PC_DXC") { + Some(p) => PathBuf::from(p), + None => victory_shader::emit::validator::Validator::default_path()? + .with_file_name("dxc.exe"), }; - t.RTFormats[..formats.len()].copy_from_slice(formats); - t + dxc.exists().then_some(dxc) } - fn blending(independent: bool) -> D3D12_BLEND_DESC { - let mut b = GraphicsState::default().blend; - b.IndependentBlendEnable = independent.into(); - for t in &mut b.RenderTarget { - t.BlendEnable = true.into(); - t.SrcBlend = D3D12_BLEND_SRC_ALPHA; - t.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; - } - b + fn compile(dxc: &Path, dir: &Path, src: &str, profile: &str) -> Vec { + let (hlsl, out) = ( + dir.join(format!("{profile}.hlsl")), + dir.join(format!("{profile}.dxil")), + ); + std::fs::write(&hlsl, src).unwrap(); + let status = std::process::Command::new(dxc) + .args(["-nologo", "-T", profile, "-E", "main", "-Fo"]) + .arg(&out) + .arg(&hlsl) + .status() + .unwrap(); + assert!(status.success(), "dxc failed for {profile}"); + std::fs::read(out).unwrap() } - #[test] - fn integer_targets_do_not_blend() { - let t = targets(&[ - DXGI_FORMAT_R8G8B8A8_UNORM, - DXGI_FORMAT_R16G16B16A16_FLOAT, - DXGI_FORMAT_R8_UINT, - ]); - for independent in [false, true] { - let host = host_blend(&blending(independent), &t); - assert!(host.IndependentBlendEnable.as_bool()); - assert!(host.RenderTarget[0].BlendEnable.as_bool()); - assert!(host.RenderTarget[1].BlendEnable.as_bool()); - assert!(!host.RenderTarget[2].BlendEnable.as_bool()); - // The rest of the target's state is the title's. - assert_eq!(host.RenderTarget[2].SrcBlend, D3D12_BLEND_SRC_ALPHA); - assert_eq!(host.RenderTarget[0].DestBlend, D3D12_BLEND_INV_SRC_ALPHA); + fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE { + D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), } } + /// A mesh pipeline made once is loaded from the library the next time, + /// not compiled again (a stream without a topology never loads). #[test] - fn blend_states_without_integer_blending_are_kept() { - // No integer target. - let b = blending(false); - let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R11G11B10_FLOAT]); - assert_eq!(host_blend(&b, &t), b); - // An integer target that does not blend. - let mut b = blending(true); - b.RenderTarget[1].BlendEnable = false.into(); - let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT]); - assert_eq!(host_blend(&b, &t), b); - // Integer formats past the targets in use. - let mut t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM]); - t.RTFormats[1] = DXGI_FORMAT_R8_UINT; - assert_eq!(host_blend(&blending(false), &t), blending(false)); - } - - /// Padding bytes after `u8` fields in title PSO streams (such as - /// `RenderTargetWriteMask` or `StencilWriteMask`) must be zeroed so - /// identical logical states produce byte-identical D3D12 structs. - #[test] - fn cleaned_graphics_descs_zero_padding_bytes() { - let mut raw_depth = [0xAAu8; size_of::()]; - let base = D3D12_DEPTH_STENCIL_DESC { - DepthEnable: true.into(), - DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, - DepthFunc: D3D12_COMPARISON_FUNC_LESS, - StencilEnable: false.into(), - StencilReadMask: 0xff, - StencilWriteMask: 0xff, - FrontFace: D3D12_DEPTH_STENCILOP_DESC::default(), - BackFace: D3D12_DEPTH_STENCILOP_DESC::default(), - }; - // Write valid fields over 0xAA garbage so only padding stays 0xAA. - // SAFETY: `raw_depth` has the exact size of `D3D12_DEPTH_STENCIL_DESC`. - let dirty: D3D12_DEPTH_STENCIL_DESC = unsafe { - let p = raw_depth.as_mut_ptr().cast::(); - std::ptr::addr_of_mut!((*p).DepthEnable).write_unaligned(base.DepthEnable); - std::ptr::addr_of_mut!((*p).DepthWriteMask).write_unaligned(base.DepthWriteMask); - std::ptr::addr_of_mut!((*p).DepthFunc).write_unaligned(base.DepthFunc); - std::ptr::addr_of_mut!((*p).StencilEnable).write_unaligned(base.StencilEnable); - std::ptr::addr_of_mut!((*p).StencilReadMask).write_unaligned(base.StencilReadMask); - std::ptr::addr_of_mut!((*p).StencilWriteMask).write_unaligned(base.StencilWriteMask); - std::ptr::addr_of_mut!((*p).FrontFace).write_unaligned(base.FrontFace); - std::ptr::addr_of_mut!((*p).BackFace).write_unaligned(base.BackFace); - p.read_unaligned() + fn a_mesh_pipeline_loads_from_the_library() { + let Some(host) = host() else { + return; // no host GPU here }; - let a = clean_depth(dirty); - let b = clean_depth(base); - // SAFETY: inspecting raw bytes of plain-old-data structs. - let (ba, bb) = unsafe { - ( - std::slice::from_raw_parts( - (&raw const a).cast::(), - size_of::(), - ), - std::slice::from_raw_parts( - (&raw const b).cast::(), - size_of::(), - ), - ) + if !host.mesh_shaders() { + eprintln!("no host mesh shader support; skipped"); + return; + } + let Some(dxc) = dxc() else { + eprintln!("no PC dxc.exe; skipped"); + return; }; - assert_eq!(ba, bb); - } - - fn read_subobject( - state: &mut GraphicsState, - kind: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, - data: T, - ) { - #[repr(C, align(8))] - struct Subobject(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); - - let subobject = Subobject(kind, data); - // SAFETY: the test supplies the payload type for the given kind and - // keeps any data it references alive for the call. - unsafe { state.read(kind.0 as u32, (&raw const subobject).cast()) }; - } - - fn read_layout(state: &mut GraphicsState, elements: &[D3D12_INPUT_ELEMENT_DESC]) { - read_subobject( - state, - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, - D3D12_INPUT_LAYOUT_DESC { - pInputElementDescs: elements.as_ptr(), - NumElements: elements.len() as u32, - }, + let dir = tempfile::tempdir().unwrap(); + let ms = compile(&dxc, dir.path(), MS, "ms_6_5"); + let ps = compile(&dxc, dir.path(), PS, "ps_6_5"); + let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap(); + let mut g = GraphicsState::default(); + // This pipeline has only a color target, with no depth buffer. + g.depth.DepthEnable = false.into(); + g.targets.NumRenderTargets = 1; + g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let name = super::super::library::name("mesh test", &root_blob, &[&ms, &ps], &g.describe()); + mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, false, &name).expect("made"); + let loaded = super::super::library::LOADED.load(Ordering::Relaxed); + mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, false, &name).expect("made again"); + assert!( + super::super::library::LOADED.load(Ordering::Relaxed) > loaded, + "the mesh pipeline was compiled again instead of loaded from the library" ); } - fn input(slot: u32, format: DXGI_FORMAT, offset: u32) -> D3D12_INPUT_ELEMENT_DESC { - D3D12_INPUT_ELEMENT_DESC { - SemanticName: PCSTR(c"SYNTHETIC".as_ptr().cast()), - Format: format, - InputSlot: slot, - AlignedByteOffset: offset, - InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, - ..Default::default() - } - } - - #[test] - fn empty_input_layout_replaces_existing_elements() { - let mut state = GraphicsState::default(); - let element = input(3, DXGI_FORMAT_R32_FLOAT, 0); - for ptr in [std::ptr::null(), &raw const element] { - read_layout(&mut state, &[element]); - assert_eq!(state.input_layout.as_ref().unwrap().slots(), 1 << 3); - - read_subobject( - &mut state, - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, - D3D12_INPUT_LAYOUT_DESC { - pInputElementDescs: ptr, - NumElements: 0, - }, - ); - let layout = state.input_layout.as_ref().unwrap(); - assert_eq!(layout.slots(), 0); - assert!(layout.elements().unwrap().is_empty()); - assert_eq!(state.describe(), GraphicsState::default().describe()); - } - } - - #[test] - fn oversized_input_layout_is_discarded() { - let mut state = GraphicsState::default(); - let element = input(0, DXGI_FORMAT_R32_FLOAT, 0); - let elements: [_; 33] = std::array::from_fn(|i| D3D12_INPUT_ELEMENT_DESC { - SemanticIndex: i as u32, - ..element - }); - read_layout(&mut state, &elements[..32]); - assert_eq!(state.input_layout.as_ref().unwrap().inputs.len(), 32); - - read_layout(&mut state, &elements); - assert!(state.input_layout.is_none()); - } - - #[test] - fn out_of_range_input_slot_is_discarded() { - let mut state = GraphicsState::default(); - read_layout(&mut state, &[input(32, DXGI_FORMAT_R32_FLOAT, 0)]); - - assert!(state.input_layout.is_none()); - } - - #[test] - fn nonempty_input_layout_requires_an_aligned_non_null_array() { - let mut state = GraphicsState::default(); - let element = input(0, DXGI_FORMAT_R32_FLOAT, 0); - let misaligned = (&raw const element).cast::().wrapping_add(1).cast(); - for ptr in [std::ptr::null(), misaligned] { - read_layout(&mut state, &[element]); - read_subobject( - &mut state, - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, - D3D12_INPUT_LAYOUT_DESC { - pInputElementDescs: ptr, - NumElements: 1, - }, - ); - assert!(state.input_layout.is_none()); - } - } + const VS: &str = "float4 main(uint i : SV_VertexID) : SV_Position { + float2 p = float2((i << 1) & 2, i & 2); + return float4(p * 2.0 - 1.0, 0.5, 1.0); + }"; + /// A graphics pipeline with `DepthBoundsTestEnable` loads back from the + /// pipeline library and culls or passes fragments according to + /// `OMSetDepthBounds` (including across a command-list cut). #[test] - fn null_semantic_name_discards_the_layout() { - let mut state = GraphicsState::default(); - let valid = input(0, DXGI_FORMAT_R32_FLOAT, 0); - let invalid = D3D12_INPUT_ELEMENT_DESC { - SemanticName: PCSTR::null(), - ..input(1, DXGI_FORMAT_R32_FLOAT, 0) + fn depth_bounds_pipeline_loads_and_filters_draws() { + let Some(host) = host() else { + return; }; - read_layout(&mut state, &[valid]); - read_layout(&mut state, &[valid, invalid]); - assert!(state.input_layout.is_none()); - assert_ne!(state.describe(), GraphicsState::default().describe()); - - read_layout(&mut state, &[valid]); - assert_eq!(state.input_layout.as_ref().unwrap().slots(), 1); - } - - #[test] - fn input_layout_owns_semantic_names_and_describes_their_values() { - let mut state = GraphicsState::default(); - let element = D3D12_INPUT_ELEMENT_DESC { - SemanticIndex: 7, - InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, - InstanceDataStepRate: 3, - ..input(2, DXGI_FORMAT(119), 12) - }; - { - let name = CString::new("SYNTHETIC").unwrap(); - let source = D3D12_INPUT_ELEMENT_DESC { - SemanticName: PCSTR(name.as_ptr().cast()), - ..element - }; - read_layout(&mut state, &[source]); - assert_ne!( - state.input_layout.as_ref().unwrap().inputs[0].SemanticName, - source.SemanticName, - ); + if !host.depth_bounds() { + eprintln!("no host depth bounds support; skipped"); + return; } - let stored = state.input_layout.as_ref().unwrap().inputs[0]; - // SAFETY: the state still owns the copied string. - let copied_name = unsafe { CStr::from_ptr(stored.SemanticName.0.cast()) }; - assert_eq!(copied_name, c"SYNTHETIC"); - assert_eq!( - stored, - D3D12_INPUT_ELEMENT_DESC { - SemanticName: stored.SemanticName, - Format: DXGI_FORMAT_R24_UNORM_X8_TYPELESS, - ..element + let Some(dxc) = dxc() else { + eprintln!("no PC dxc.exe; skipped"); + return; + }; + let dir = tempfile::tempdir().unwrap(); + let vs = compile(&dxc, dir.path(), VS, "vs_6_5"); + let ps = compile(&dxc, dir.path(), PS, "ps_6_5"); + let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap(); + + let mut g = GraphicsState::default(); + // Subobject 21 (`DEPTH_STENCIL1`) with `DepthBoundsTestEnable = true`, + // depth test itself off so only depth bounds gates the draw. + #[repr(C, align(8))] + struct Sub21(u32, D3D12_DEPTH_STENCIL_DESC1); + let sub = Sub21( + 21, + D3D12_DEPTH_STENCIL_DESC1 { + DepthEnable: false.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, + DepthBoundsTestEnable: true.into(), + ..Default::default() }, ); + // SAFETY: `sub` is a complete subobject 21. + unsafe { g.read(21, (&raw const sub).cast()) }; + assert!(g.depth_bounds); + assert!(g.describe().contains("depth-bounds")); + g.rasterizer.CullMode = D3D12_CULL_MODE_NONE; + g.targets.NumRenderTargets = 1; + g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + g.depth_format = DXGI_FORMAT_D32_FLOAT; - let mut other = GraphicsState::default(); - read_layout(&mut other, &[element]); - assert_eq!(state.describe(), other.describe()); - read_layout( - &mut other, - &[D3D12_INPUT_ELEMENT_DESC { - SemanticName: PCSTR(c"OTHER".as_ptr().cast()), - ..element - }], - ); - assert_ne!(state.describe(), other.describe()); - } - - #[test] - fn appended_inputs_respect_format_alignment_per_slot() { - let mut state = GraphicsState::default(); - let append = D3D12_APPEND_ALIGNED_ELEMENT; - let mut instance = input(31, DXGI_FORMAT_R16_UINT, append); - instance.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; - instance.InstanceDataStepRate = 2; - let mut instance_next = instance; - instance_next.Format = DXGI_FORMAT_R32_FLOAT; - read_layout( - &mut state, - &[ - input(0, DXGI_FORMAT_R8_UINT, 0), - instance, - input(0, DXGI_FORMAT_R16_UINT, append), - instance_next, - input(0, DXGI_FORMAT_R32G32B32_FLOAT, append), - input(0, DXGI_FORMAT_R8_UINT, append), - input(0, DXGI_FORMAT_R32_FLOAT, 24), - input(0, DXGI_FORMAT_R32_FLOAT, append), - ], - ); - - let layout = state.input_layout.as_ref().unwrap(); - assert_eq!(layout.slots(), 1 | (1 << 31)); - let elements = layout.elements().unwrap(); - let locations: Vec<_> = elements - .iter() - .map(|e| (e.slot, e.offset, e.format, e.per_instance)) - .collect(); - assert_eq!( - locations, - [ - (0, 0, 62, false), - (31, 0, 57, true), - (0, 2, 57, false), - (31, 4, 41, true), - (0, 4, 6, false), - (0, 16, 62, false), - (0, 24, 41, false), - (0, 28, 41, false), - ], + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: borrowed pointer, never released by the descriptor. + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + VS: code(&vs), + PS: code(&ps), + BlendState: g.blend, + SampleMask: g.sample_mask, + RasterizerState: g.rasterizer, + DepthStencilState: g.depth, + IBStripCutValue: g.strip_cut, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: g.targets.RTFormats, + DSVFormat: g.depth_format, + SampleDesc: g.samples, + ..Default::default() + }; + let name = super::super::library::name( + "graphics depth-bounds test", + &root_blob, + &[&vs, &ps], + &g.describe(), ); - } - - #[test] - fn input_offset_overflow_is_rejected() { - let mut state = GraphicsState::default(); - read_layout(&mut state, &[input(0, DXGI_FORMAT_R32_FLOAT, u32::MAX - 3)]); - assert!(state.input_layout.as_ref().unwrap().elements().is_none()); - - read_layout( - &mut state, - &[ - input(0, DXGI_FORMAT_R8_UINT, u32::MAX - 1), - input(0, DXGI_FORMAT_R32_FLOAT, D3D12_APPEND_ALIGNED_ELEMENT), - ], + let pso = graphics_depth_bounds_pipeline(&host.device, &root, &desc, g.depth1(), &name) + .expect("depth-bounds PSO made"); + let loaded = super::super::library::LOADED.load(Ordering::Relaxed); + graphics_depth_bounds_pipeline(&host.device, &root, &desc, g.depth1(), &name) + .expect("depth-bounds PSO made again"); + assert!( + super::super::library::LOADED.load(Ordering::Relaxed) > loaded, + "the depth-bounds pipeline was compiled again instead of loaded from the library" ); - assert!(state.input_layout.as_ref().unwrap().elements().is_none()); - } - #[test] - fn omitted_subobjects_use_d3d12_defaults() { - let state = GraphicsState::default(); - assert!(!state.blend.AlphaToCoverageEnable.as_bool()); - assert!(!state.blend.IndependentBlendEnable.as_bool()); - for target in state.blend.RenderTarget { - assert!(!target.BlendEnable.as_bool()); - assert!(!target.LogicOpEnable.as_bool()); - assert_eq!(target.SrcBlend, D3D12_BLEND_ONE); - assert_eq!(target.DestBlend, D3D12_BLEND_ZERO); - assert_eq!(target.BlendOp, D3D12_BLEND_OP_ADD); - assert_eq!(target.SrcBlendAlpha, D3D12_BLEND_ONE); - assert_eq!(target.DestBlendAlpha, D3D12_BLEND_ZERO); - assert_eq!(target.BlendOpAlpha, D3D12_BLEND_OP_ADD); - assert_eq!(target.LogicOp, D3D12_LOGIC_OP_NOOP); - assert_eq!(target.RenderTargetWriteMask, 0xf); - } - assert_eq!(state.sample_mask, u32::MAX); - assert_eq!(state.rasterizer.FillMode, D3D12_FILL_MODE_SOLID); - assert_eq!(state.rasterizer.CullMode, D3D12_CULL_MODE_BACK); - assert!(!state.rasterizer.FrontCounterClockwise.as_bool()); - assert!(state.rasterizer.DepthClipEnable.as_bool()); - assert_eq!(state.rasterizer.DepthBias, 0); - assert!(state.depth.DepthEnable.as_bool()); - assert_eq!(state.depth.DepthWriteMask, D3D12_DEPTH_WRITE_MASK_ALL); - assert_eq!(state.depth.DepthFunc, D3D12_COMPARISON_FUNC_LESS); - assert!(!state.depth.StencilEnable.as_bool()); - assert_eq!(state.depth.StencilReadMask, 0xff); - assert_eq!(state.depth.StencilWriteMask, 0xff); - for face in [state.depth.FrontFace, state.depth.BackFace] { - assert_eq!(face.StencilFailOp, D3D12_STENCIL_OP_KEEP); - assert_eq!(face.StencilDepthFailOp, D3D12_STENCIL_OP_KEEP); - assert_eq!(face.StencilPassOp, D3D12_STENCIL_OP_KEEP); - assert_eq!(face.StencilFunc, D3D12_COMPARISON_FUNC_ALWAYS); - } - assert_eq!(state.strip_cut, D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED); - assert_eq!(state.topology, D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED); - assert_eq!(state.targets.NumRenderTargets, 0); - assert_eq!(state.targets.RTFormats, [DXGI_FORMAT_UNKNOWN; 8]); - assert_eq!(state.depth_format, DXGI_FORMAT_UNKNOWN); - assert_eq!( - state.samples, - DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0 + // Execute two draws against a depth buffer cleared to 0.5: + // 1) bounds [0.6, 1.0] -> rejected (target stays 0) + // 2) bounds [0.4, 0.6] replayed onto a fresh HostList -> passes (target becomes 255) + let make_tex = |format, flags, state, clear: D3D12_CLEAR_VALUE| { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 4, + Height: 4, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: valid heap and resource descriptions. + unsafe { + host.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &rd, state, Some(&clear), &mut out) + .unwrap(); } - ); - } - - #[test] - fn reads_blend_and_rasterizer_state() { - let mut state = GraphicsState::default(); - let mut blend = D3D12_BLEND_DESC { - AlphaToCoverageEnable: true.into(), - IndependentBlendEnable: true.into(), - RenderTarget: state.blend.RenderTarget, - }; - blend.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC { - BlendEnable: true.into(), - SrcBlend: D3D12_BLEND_SRC_ALPHA, - DestBlend: D3D12_BLEND_INV_SRC_ALPHA, - BlendOp: D3D12_BLEND_OP_REV_SUBTRACT, - SrcBlendAlpha: D3D12_BLEND_DEST_ALPHA, - DestBlendAlpha: D3D12_BLEND_INV_DEST_ALPHA, - BlendOpAlpha: D3D12_BLEND_OP_MAX, - RenderTargetWriteMask: 0x5, - ..blend.RenderTarget[0] + out.unwrap() }; - blend.RenderTarget[7].LogicOpEnable = true.into(); - blend.RenderTarget[7].LogicOp = D3D12_LOGIC_OP_XOR; - let raster = D3D12_RASTERIZER_DESC { - FillMode: D3D12_FILL_MODE_WIREFRAME, - CullMode: D3D12_CULL_MODE_FRONT, - FrontCounterClockwise: true.into(), - DepthBias: -7, - DepthBiasClamp: 0.5, - SlopeScaledDepthBias: -1.25, - DepthClipEnable: false.into(), - MultisampleEnable: true.into(), - AntialiasedLineEnable: true.into(), - ForcedSampleCount: 4, - ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON, - }; - read_subobject(&mut state, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, blend); - read_subobject( - &mut state, - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, - raster, - ); - assert_eq!(state.blend, blend); - assert_eq!(state.rasterizer, raster); - } - - #[test] - fn reads_both_depth_stencil_subobjects() { - let mut state = GraphicsState::default(); - let depth = D3D12_DEPTH_STENCIL_DESC { - DepthEnable: false.into(), - DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, - DepthFunc: D3D12_COMPARISON_FUNC_GREATER, - StencilEnable: true.into(), - StencilReadMask: 0x31, - StencilWriteMask: 0xe7, - FrontFace: D3D12_DEPTH_STENCILOP_DESC { - StencilFailOp: D3D12_STENCIL_OP_ZERO, - StencilDepthFailOp: D3D12_STENCIL_OP_REPLACE, - StencilPassOp: D3D12_STENCIL_OP_INCR_SAT, - StencilFunc: D3D12_COMPARISON_FUNC_EQUAL, - }, - BackFace: D3D12_DEPTH_STENCILOP_DESC { - StencilFailOp: D3D12_STENCIL_OP_INVERT, - StencilDepthFailOp: D3D12_STENCIL_OP_DECR, - StencilPassOp: D3D12_STENCIL_OP_INCR, - StencilFunc: D3D12_COMPARISON_FUNC_NOT_EQUAL, - }, - }; - let depth1 = D3D12_DEPTH_STENCIL_DESC1 { - DepthEnable: true.into(), - DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, - DepthFunc: D3D12_COMPARISON_FUNC_GREATER_EQUAL, - StencilEnable: false.into(), - StencilReadMask: 0x52, - StencilWriteMask: 0xa5, - FrontFace: depth.BackFace, - BackFace: depth.FrontFace, - DepthBoundsTestEnable: true.into(), - }; - read_subobject( - &mut state, - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, - depth, - ); - assert_eq!(state.depth, depth); - read_subobject( - &mut state, - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, - depth1, - ); - assert_eq!( - state.depth, - D3D12_DEPTH_STENCIL_DESC { - DepthEnable: true.into(), - DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, - DepthFunc: D3D12_COMPARISON_FUNC_GREATER_EQUAL, - StencilEnable: false.into(), - StencilReadMask: 0x52, - StencilWriteMask: 0xa5, - FrontFace: depth.BackFace, - BackFace: depth.FrontFace, + let color = make_tex( + DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0; 4] }, }, ); - } - - #[test] - fn translates_render_target_and_depth_formats() { - let mut state = GraphicsState::default(); - let mut formats = [DXGI_FORMAT_R8G8B8A8_UNORM; 8]; - formats[6] = DXGI_FORMAT(119); - formats[7] = DXGI_FORMAT(120); - read_subobject( - &mut state, - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, - D3D12_RT_FORMAT_ARRAY { - RTFormats: formats, - NumRenderTargets: 8, + let depth = make_tex( + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_D32_FLOAT, + Anonymous: D3D12_CLEAR_VALUE_0 { + DepthStencil: D3D12_DEPTH_STENCIL_VALUE { + Depth: 0.5, + Stencil: 0, + }, + }, }, ); - formats[6] = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; - formats[7] = DXGI_FORMAT_X24_TYPELESS_G8_UINT; - assert_eq!(state.targets.NumRenderTargets, 8); - assert_eq!(state.targets.RTFormats, formats); - - for (title, native) in [ - (118, DXGI_FORMAT_D24_UNORM_S8_UINT), - (40, DXGI_FORMAT_D32_FLOAT), - (0, DXGI_FORMAT_UNKNOWN), - ] { - read_subobject( - &mut state, - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, - DXGI_FORMAT(title), - ); - assert_eq!(state.depth_format, native); - } - } - - #[test] - fn reads_scalar_and_sample_state_and_ignores_unknown_subobjects() { - let mut state = GraphicsState::default(); - let mut storage = [0u64; 2]; - let kind = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK.0 as u32; - let at = storage.as_mut_ptr().cast::().wrapping_add(1); - let mask = 0xfe01_1234u32; - // SAFETY: both u32 writes are inside the storage at the stream's - // type/data offsets. The read is of that whole subobject. - unsafe { - at.cast::().write_unaligned(kind); - at.add(4).cast::().write_unaligned(mask); - state.read(kind, at); - } - assert_eq!(state.sample_mask, mask); - - let strip_cut = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF; - let topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; - let samples = DXGI_SAMPLE_DESC { - Count: 4, - Quality: 3, + let readback = { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: valid readback buffer description. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &rd, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut out, + ) + .unwrap(); + } + out.unwrap() }; - read_subobject( - &mut state, - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, - strip_cut, - ); - read_subobject( - &mut state, - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, - topology, - ); - read_subobject( - &mut state, - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, - samples, - ); - assert_eq!(state.strip_cut, strip_cut); - assert_eq!(state.topology, topology); - assert_eq!(state.samples, samples); - let before = state.describe(); - read_subobject(&mut state, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(99), 0u32); - assert_eq!(state.describe(), before); - } - - #[test] - fn shader_bytecode_is_copied_by_length() { - assert!(code_bytes(&D3D12_SHADER_BYTECODE::default()).is_empty()); - let copy = { - let bytes = [8u8, 0, 32, 91]; - let mut desc = D3D12_SHADER_BYTECODE { - pShaderBytecode: bytes.as_ptr().cast(), - BytecodeLength: 0, + let run_draw = |min: f32, max: f32| -> u8 { + let mut state = crate::draw::State::default(); + let first_list = host.new_list().unwrap(); + state.set_depth_bounds(&first_list, min, max); + first_list.close(); + // Replay onto a second host list, exercising `State::replay`. + let list = host.new_list().unwrap(); + state.replay(&list); + let rtv = host.rtv(Some(&color), None); + let dsv = host.dsv(&depth, None); + let vp = D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: 4.0, + Height: 4.0, + MinDepth: 0.0, + MaxDepth: 1.0, }; - assert!(code_bytes(&desc).is_empty()); - desc.BytecodeLength = 3; - code_bytes(&desc) + let rect = windows::Win32::Foundation::RECT { + left: 0, + top: 0, + right: 4, + bottom: 4, + }; + // SAFETY: open command list, live resources and views. + unsafe { + list.list.ClearRenderTargetView(rtv, &[0.0; 4], None); + list.list.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 0.5, 0, None); + list.list.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv)); + list.list.RSSetViewports(&[vp]); + list.list.RSSetScissorRects(&[rect]); + list.list.SetGraphicsRootSignature(&root); + list.list.SetPipelineState(&pso); + list.list + .IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list.list.DrawInstanced(3, 1, 0, 0); + list.list.ResourceBarrier(&[crate::host::transition( + &color, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&color), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + list.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.list.ResourceBarrier(&[crate::host::transition( + &color, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET, + )]); + } + list.close(); + host.execute(&[&list]); + let mut ptr = std::ptr::null_mut(); + // SAFETY: `execute` waited for the GPU; readback holds 1024 bytes. + unsafe { + readback.Map(0, None, Some(&mut ptr)).unwrap(); + let pixel = *ptr.cast::(); + readback.Unmap(0, None); + pixel + } }; - assert_eq!(copy, [8, 0, 32]); + + // The software adapter reports depth-bounds support but does not + // enforce it; on such a host there is nothing more to check here. + if run_draw(0.6, 1.0) != 0 { + eprintln!("host does not enforce the depth bounds test; skipped"); + return; + } + assert_eq!(run_draw(0.4, 0.6), 255, "depth 0.5 inside [0.4, 0.6] must pass"); } } diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 85f0764..fac6f59 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -5,25 +5,52 @@ //! a hash of all that its host description holds (the translated //! shaders' code, which changes when a translation does, our root //! signature, the graphics state). The library is saved under the cache -//! folder in [`SHARDS`] files, chosen by that name; the host refuses a -//! library of another adapter or driver, and an entry whose description -//! differs, so neither is ever used. A save serialises and writes only -//! the shards that gained pipelines, because the host can only serialise -//! a library whole and one blob of the world's pipelines is over 600 MB. +//! folder; the host refuses a library of another adapter or driver, and +//! an entry whose description differs, so neither is ever used. //! 2. The title pipelines a run drew or dispatched with are listed by a key //! known when the title creates them (their shader containers and //! graphics state); the next run hands those to the workers at //! creation, during loading. //! -//! Stores and serialising are serialised. Loads run outside that lock on a -//! reference of the library's own: vkd3d-proton keeps no compiled code in its -//! library, so there a load is a whole compile and holding the lock would make -//! the workers wait for one another. +//! Library calls overlap: the host documents the library as safe to use +//! from several threads ("The pipeline library is thread-safe to use, and +//! will internally synchronize as necessary", `CreatePipelineLibrary`, +//! Thread Safety), with one exception kept here: two loads of the same +//! pipeline are made one after the other ([`same_name`]). Under one lock of +//! ours for every call, the eight workers made pipelines one at a time: +//! 87 to 96 of 110 looks at each worker found it waiting for that lock +//! (run 49), and an earlier run's 2,300 pipelines, all in the library, were +//! still being loaded 46 s into the opening cutscene. +//! `VICTORY_LIBRARY_LOCK=1`: one call at a time, as before. +//! +//! The library's file is mapped, not read into memory ([`Blob`]): the host +//! keeps pointing into the bytes it was made from for as long as it lives, +//! and read into a buffer they were 1,352 MB of the process's own memory +//! for the whole run (run 60), all of it in physical memory. Mapped, the +//! pages are the file's: only those the host reads are in memory, and the +//! system can drop them without writing them anywhere. A save writes the +//! new library through a mapping of the new file in the same way (a buffer +//! of the library's size was made, filled and written out at each save). +//! `VICTORY_LIBRARY_MAP=0`: read and written through buffers, as before. +//! +//! The mapped file's handle stays open for as long as the mapping lives +//! ([`holds`]). A save renames the new library over the file this run has +//! mapped, and with the handle closed Windows then gives up the old file's +//! contents: every page of the mapping that is not in memory at that +//! moment, or leaves memory later (the trim below, or Windows taking pages +//! back), reads as zeros from then on. The host's library reads such pages +//! as stored pipelines; the driver, handed a pipeline of zeros, removes the +//! device with DXGI_ERROR_DRIVER_INTERNAL_ERROR (runs 72, 73 and 82, each +//! within 5 ms of the first library call after a save and a trim; and the +//! library run 77 saved from such pages was refused by run 78). Measured +//! with a 64 MB file written past the system's cache, mapped and replaced: +//! 16,352 of 16,384 pages read zeros with the handle closed, none with it +//! open (the test below). `VICTORY_LIBRARY_HANDLE=0`: closed, as before. -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, LazyLock, Mutex, OnceLock}; +use std::sync::{Mutex, MutexGuard, OnceLock, RwLock}; use windows::Win32::Graphics::Direct3D12::*; use windows::core::{HSTRING, Interface, PCWSTR}; @@ -40,120 +67,432 @@ pub fn use_pipeline_cache(dir: PathBuf) { pub(crate) static MADE: AtomicU64 = AtomicU64::new(0); pub(crate) static LOADED: AtomicU64 = AtomicU64::new(0); pub(crate) static EARLY: AtomicU64 = AtomicU64::new(0); +/// For the memory lines: the bytes of the library's file, kept in memory +/// while the library lives, and the bytes the last save wrote (a buffer of +/// that size is made, filled and written every time pipelines were added, +/// at most every 20 s). +pub(crate) static BLOB: AtomicU64 = AtomicU64::new(0); +pub(crate) static SAVED: AtomicU64 = AtomicU64::new(0); + +/// Whether the library's file is mapped ([`Blob`]) and saved through a +/// mapping. On by default; `VICTORY_LIBRARY_MAP=0` uses buffers, as before. +fn mapped() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_MAP").is_none_or(|v| v != "0")) +} + +/// Whether the mapped library file's handle is kept open while it is +/// mapped (see the module's notes: without it a save in the same run turns +/// the mapping's pages into zeros as they leave memory). On by default; +/// `VICTORY_LIBRARY_HANDLE=0` closes it after mapping, as before. +fn holds() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_HANDLE").is_none_or(|v| v != "0")) +} + +/// A whole file mapped into memory: read-only (the library's file) or +/// writable (the file a save fills). Unmapped when dropped. +struct Mapped { + at: windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS, + len: usize, + /// The file, for a mapping made by [`Mapped::open`] ([`holds`]): open + /// until after the view is unmapped, so that the file a rename took + /// the name from keeps its contents for the view. + _file: Option, +} + +impl Mapped { + /// Maps `file` (`len` bytes, not zero) for reading, or for reading and + /// writing. + fn map(file: &std::fs::File, len: usize, write: bool) -> Option { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_READ, FILE_MAP_WRITE, MapViewOfFile, PAGE_READONLY, PAGE_READWRITE, + }; + if len == 0 { + return None; + } + // SAFETY: a file we hold open; the view keeps the file's pages + // after the mapping object and the file are closed. + let at = unsafe { + let mapping = CreateFileMappingW( + file.as_raw_handle(), + std::ptr::null(), + if write { PAGE_READWRITE } else { PAGE_READONLY }, + 0, + 0, + std::ptr::null(), + ); + if mapping.is_null() { + return None; + } + let at = MapViewOfFile(mapping, if write { FILE_MAP_WRITE } else { FILE_MAP_READ }, 0, 0, 0); + CloseHandle(mapping); + at + }; + (!at.Value.is_null()).then_some(Mapped { at, len, _file: None }) + } + + /// The file at `path`, mapped for reading; `None` if it is not there, + /// is empty or cannot be mapped. + fn open(path: &std::path::Path) -> Option { + Mapped::open_holding(path, holds()) + } + + /// As [`Mapped::open`]; `hold` says whether the file stays open with + /// the mapping. + fn open_holding(path: &std::path::Path, hold: bool) -> Option { + // Opened as the standard library opens a file to read: others may + // read, write, rename and delete it meanwhile, so a save still + // renames the new library over this one. + let file = std::fs::File::open(path).ok()?; + let len = usize::try_from(file.metadata().ok()?.len()).ok()?; + let mut mapped = Mapped::map(&file, len, false)?; + if hold { + mapped._file = Some(file); + } + Some(mapped) + } + + /// A new file of `len` bytes at `path` (replacing what is there), + /// mapped for writing. + fn create(path: &std::path::Path, len: usize) -> Option { + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(path) + .ok()?; + file.set_len(len as u64).ok()?; + Mapped::map(&file, len, true) + } + + fn bytes(&self) -> &[u8] { + // SAFETY: the view holds `len` readable bytes until dropped. + unsafe { std::slice::from_raw_parts(self.at.Value.cast(), self.len) } + } + + /// Only for a view made by [`Mapped::create`]. + fn bytes_mut(&mut self) -> &mut [u8] { + // SAFETY: a writable view of `len` bytes, ours alone. + unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) } + } +} + +impl Drop for Mapped { + fn drop(&mut self) { + // SAFETY: our view. + unsafe { windows_sys::Win32::System::Memory::UnmapViewOfFile(self.at) }; + } +} + +/// The bytes a library is made from: the host reads them for as long as +/// the library lives, so they are kept beside it. +enum Blob { + /// No file (an empty library). + None, + /// The file read into memory (`VICTORY_LIBRARY_MAP=0`, tests, or a file + /// that could not be mapped). + Held(Vec), + /// The file itself, mapped. + Mapped(Mapped), +} + +impl Blob { + /// The library file in `dir`: a library a save left beside it + /// ([`NEXT_FILE`]) takes its place first. + fn of(dir: &std::path::Path) -> Blob { + let path = dir.join(LIBRARY_FILE); + let next = dir.join(NEXT_FILE); + if next.exists() && std::fs::rename(&next, &path).is_err() { + tracing::warn!("the host pipeline library saved last could not take the old one's place"); + } + if mapped() + && let Some(file) = Mapped::open(&path) + { + return Blob::Mapped(file); + } + match std::fs::read(&path) { + Ok(bytes) if !bytes.is_empty() => Blob::Held(bytes), + _ => Blob::None, + } + } + + fn bytes(&self) -> &[u8] { + match self { + Blob::None => &[], + Blob::Held(bytes) => bytes, + Blob::Mapped(file) => file.bytes(), + } + } +} + +/// The mapped library file's view (address, bytes; 0: not mapped), when a +/// pipeline was last loaded from the library (`crate::host::now_ms`), and +/// whether the view's pages were let go since ([`trim`]). +static VIEW: [std::sync::atomic::AtomicUsize; 2] = [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; +static LOADED_AT: AtomicU64 = AtomicU64::new(0); +static TRIMMED: AtomicBool = AtomicBool::new(false); +/// The bytes of the view let go so far, for the memory line. +pub(crate) static TRIMMED_BYTES: AtomicU64 = AtomicU64::new(0); +/// When the view's pages were last let go (`crate::host::now_ms`), and how +/// often and when a save of this run last renamed a new library over the +/// mapped file: for [`removal_note`]. +static TRIMMED_AT: AtomicU64 = AtomicU64::new(0); +static REPLACED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// The library calls running now: thread, what (load, make, store, +/// serialise), the pipeline, and since when (`crate::host::now_us`). +static CALLS: Mutex> = Mutex::new(Vec::new()); + +thread_local! { + /// The pipeline this thread is making (its shaders), for [`CALLS`]. + static LABEL: std::cell::RefCell = const { std::cell::RefCell::new(String::new()) }; +} + +/// Names the pipeline this thread makes next. +pub(crate) fn label(text: String) { + LABEL.with(|l| *l.borrow_mut() = text); +} + +/// A library call of this thread, listed in [`CALLS`] until dropped. +struct Call(u32, u64); + +fn call(what: &'static str, name: &str) -> Call { + let (thread, since) = (crate::host::thread_id(), crate::host::now_us()); + let label = LABEL.with(|l| l.borrow().clone()); + CALLS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((thread, what, format!("{name} {label}"), since)); + Call(thread, since) +} + +impl Drop for Call { + fn drop(&mut self) { + CALLS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|c| (c.0, c.3) != (self.0, self.1)); + } +} + +/// For the report when the host device is removed: the library calls +/// running at that moment, whether this run replaced the mapped file and +/// let its pages go, and how many pages of the mapping read as zeros now. +/// A library holds no page of zeros (the 259 MB one of run 83 has no run of +/// 2,048 zero bytes): each such page is one whose contents were lost (see +/// the module's notes), and a pipeline stored there is what the driver was +/// handed. +pub(crate) fn removal_note() -> String { + use std::fmt::Write; + let now = crate::host::now_us(); + let mut text = String::from("pipeline library: "); + { + let calls = CALLS.lock().unwrap_or_else(|e| e.into_inner()); + if calls.is_empty() { + text.push_str("no call running"); + } + for (i, (thread, what, name, since)) in calls.iter().enumerate() { + let _ = write!( + text, + "{}{what} of {name} running for {:.1} ms on thread {thread}", + if i == 0 { "" } else { ", " }, + now.saturating_sub(*since) as f64 / 1000.0 + ); + } + } + let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed)); + if at == 0 { + text.push_str("; its file is not mapped"); + return text; + } + let ago = |ms: u64| crate::host::now_ms().saturating_sub(ms) as f64 / 1000.0; + let _ = write!( + text, + "; its file is mapped ({len} bytes), the handle {}", + if holds() { "kept open" } else { "closed (VICTORY_LIBRARY_HANDLE=0)" } + ); + match REPLACED[0].load(Ordering::Relaxed) { + 0 => text.push_str("; this run has not replaced the file"), + n => { + let _ = write!( + text, + "; this run replaced the file under the mapping {n} times, last {:.1} s ago", + ago(REPLACED[1].load(Ordering::Relaxed)) + ); + } + } + if TRIMMED_BYTES.load(Ordering::Relaxed) > 0 { + let _ = write!(text, "; its pages were last let go {:.1} s ago", ago(TRIMMED_AT.load(Ordering::Relaxed))); + } + // Within two seconds: pages not in memory come from the disk. + let started = std::time::Instant::now(); + // SAFETY: the view lives as long as the library, which is never dropped. + let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, len) }; + let (mut zero, mut looked, mut first) = (0u64, 0u64, None); + for (n, page) in bytes.chunks(4096).enumerate() { + if n % 4096 == 0 && started.elapsed() > std::time::Duration::from_secs(2) { + break; + } + looked += 1; + if page.iter().all(|&b| b == 0) { + zero += 1; + if first.is_none() { + first = Some(n); + } + } + } + let _ = write!(text, "; {zero} of the {looked} pages looked at read as zeros now"); + if let Some(first) = first { + let _ = write!(text, " (the first is page {first}): the library's contents were lost there"); + } + text +} + +/// Lets the mapped library file's pages go from the process's memory once +/// no pipeline has been loaded for ten seconds. The host reads nearly the +/// whole file while the early pipelines load (run 65: all 1,490 MB of it +/// were in the process's memory a minute in, and 1,300 MB still at the +/// end, on a PC with 2 GB free); after that it reads the file again only +/// when a new pipeline loads. Pages let go stay in Windows' file cache +/// while nothing else wants the memory, and come back on the next read. +/// Called once a second by the sweep; does its work on a thread of its own +/// (hundreds of thousands of pages), once after each burst of loads. +/// `VICTORY_LIBRARY_TRIM=0`: the pages stay until Windows takes them. +pub(crate) fn trim() { + static ON: OnceLock = OnceLock::new(); + let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed)); + if at == 0 + || TRIMMED.load(Ordering::Relaxed) + || !*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_TRIM").is_none_or(|v| v != "0")) + { + return; + } + let quiet_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + if crate::host::now_ms() < LOADED_AT.load(Ordering::Relaxed) + quiet_ms + || TRIMMED.swap(true, Ordering::Relaxed) + { + return; + } + let work = move || { + // SAFETY: the view lives as long as the library, which is never + // dropped. Unlocking pages that are not locked fails, as expected, + // and takes them out of the working set: the documented way to let + // pages of a mapped file go. + unsafe { windows_sys::Win32::System::Memory::VirtualUnlock(at as *const _, len) }; + TRIMMED_BYTES.fetch_add(len as u64, Ordering::Relaxed); + TRIMMED_AT.store(crate::host::now_ms(), Ordering::Relaxed); + crate::host::trail(|| format!("pipeline library: the mapped file's pages let go from memory ({len} bytes)")); + }; + if std::thread::Builder::new().name("victory-library-trim".into()).spawn(work).is_err() { + TRIMMED.store(false, Ordering::Relaxed); + } +} struct Library { library: ID3D12PipelineLibrary1, /// The blob the library was made from: it must outlive the library. - _blob: Vec, + _blob: Blob, /// Pipelines stored since the last save. - added: u64, - /// Names already stored during this run (avoids duplicate `StorePipeline` - /// calls when two worker threads compile the same pipeline concurrently). - stored: HashSet, + added: AtomicU64, + /// Stores share it and a save takes it alone: the size the library + /// asks for must still be its size when it is written out. + saving: RwLock<()>, } -// SAFETY: D3D12 pipeline libraries are internally synchronised except for -// same-name loads, which `LOADS` serialises; stores and serialising are under -// the mutex that holds the library. +// SAFETY: D3D12 objects are free-threaded, and the library synchronises +// its own calls (see the module's notes); what it does not, two loads of +// one name, is serialised by `same_name`. unsafe impl Send for Library {} +// SAFETY: as above; the other fields are an atomic and a lock. +unsafe impl Sync for Library {} -/// How many files the library is split into. A save serialises and writes -/// only the shards that gained pipelines; see the module comment. -const SHARDS: usize = 16; -const EARLY_FILE: &str = "early-pipelines.txt"; -/// Loads of the same pipeline serialise (the host documents that one as not -/// thread-safe); loads of different pipelines may overlap. -static LOADS: LazyLock>>>> = - LazyLock::new(|| Mutex::new(HashMap::new())); -/// Title pipelines listed for an early start, at most. -const EARLY_MAX: usize = 8192; - -/// The file shard `shard` is kept in. -fn shard_file(shard: usize) -> String { - format!("host-pipelines.{shard:02}.bin") +/// Held by a load of the pipeline named `name`: loads of the same name +/// wait for each other (the host's one exception to the library's thread +/// safety: such a load may change that pipeline's entry). Names share 64 +/// locks, so two different names seldom wait. +fn same_name(name: &str) -> MutexGuard<'static, ()> { + static LOADING: [Mutex<()>; 64] = [const { Mutex::new(()) }; 64]; + let at = name.bytes().fold(0usize, |h, b| h.wrapping_mul(31).wrapping_add(usize::from(b))); + LOADING[at % LOADING.len()].lock().unwrap_or_else(|e| e.into_inner()) } -/// The shard a pipeline named `name` belongs to. The name is a hash, so this -/// is spread and stable across runs: a pipeline always lands in the same -/// file, which is what lets a save write only the files that changed. -fn shard_of(name: &str) -> usize { - let mut h = 0u32; - for b in name.bytes() { - h = h.wrapping_mul(31).wrapping_add(u32::from(b)); - } - h as usize % SHARDS +/// With `VICTORY_LIBRARY_LOCK=1`: held by every library call, as before. +fn one_call() -> Option> { + static ON: OnceLock = OnceLock::new(); + static CALLING: Mutex<()> = Mutex::new(()); + ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_LOCK").is_some_and(|v| v == "1")) + .then(|| CALLING.lock().unwrap_or_else(|e| e.into_inner())) } -/// One save at a time: serialising and publishing must not interleave, or an -/// older complete snapshot could be published over a newer one. -static SAVING: Mutex<()> = Mutex::new(()); +const LIBRARY_FILE: &str = "host-pipelines.bin"; +/// A saved library that could not replace [`LIBRARY_FILE`] while this run +/// had it mapped (a system that refuses to replace a mapped file): the next +/// start renames it over the library first ([`Blob::of`]). +const NEXT_FILE: &str = "host-pipelines.next"; +const EARLY_FILE: &str = "early-pipelines.txt"; +/// Title pipelines listed for an early start, at most. +const EARLY_MAX: usize = 8192; -fn libraries() -> Option<&'static [Mutex; SHARDS]> { - static LIBRARIES: OnceLock; SHARDS]>> = OnceLock::new(); - LIBRARIES +fn library() -> Option<&'static Library> { + static LIBRARY: OnceLock> = OnceLock::new(); + LIBRARY .get_or_init(|| { let device = crate::host::host()?.device.cast::().ok()?; - let read = |file| DIR.get().and_then(|d| std::fs::read(d.join(file)).ok()); - let mut shards = Vec::with_capacity(SHARDS); - for shard in 0..SHARDS { - let blob = read(shard_file(shard)).unwrap_or_default(); - shards.push(Mutex::new(open(&device, blob)?)); + let blob = DIR.get().map_or(Blob::None, |d| Blob::of(d)); + let library = open(&device, blob); + if library.is_none() { + tracing::warn!("no host pipeline library: pipelines are not kept"); } - shards.try_into().ok() + library }) .as_ref() } /// The library in `blob`, or an empty one if the host rejects the blob (an /// adapter or driver change, damage). -fn open(device: &ID3D12Device1, blob: Vec) -> Option { +fn open(device: &ID3D12Device1, blob: Blob) -> Option { let make = |bytes: &[u8]| -> windows::core::Result { - // An empty library is asked for with a null blob: an empty slice's - // pointer is dangling, which vkd3d-proton (Proton) rejects. - let data = if bytes.is_empty() { - std::ptr::null() - } else { - bytes.as_ptr() - }; - let mut library: Option = None; - // SAFETY: the bytes outlive the library (kept beside it); the out - // pointer is ours and typed by the interface id passed with it. + // SAFETY: the bytes outlive the library (kept beside it). unsafe { - (Interface::vtable(device).CreatePipelineLibrary)( - Interface::as_raw(device), - data.cast(), - bytes.len(), - &ID3D12PipelineLibrary::IID, - (&raw mut library).cast(), - ) - .ok()?; + device.CreatePipelineLibrary::(bytes)?.cast() } - library.ok_or_else(windows::core::Error::empty)?.cast() }; - if !blob.is_empty() { - match make(&blob) { + if !blob.bytes().is_empty() { + match make(blob.bytes()) { Ok(library) => { - tracing::info!(bytes = blob.len(), "host pipeline library loaded"); + let bytes = blob.bytes().len(); + BLOB.store(bytes as u64, Ordering::Relaxed); + tracing::info!(bytes, mapped = matches!(blob, Blob::Mapped(_)), "host pipeline library loaded"); + if let Blob::Mapped(file) = &blob { + VIEW[1].store(file.len, Ordering::Relaxed); + VIEW[0].store(file.at.Value as usize, Ordering::Relaxed); + LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed); + } return Some(Library { library, _blob: blob, - added: 0, - stored: HashSet::new(), + added: AtomicU64::new(0), + saving: RwLock::new(()), }); } - Err(e) => { - tracing::info!(error = %e, "host pipeline library rejected; starting an empty one") - } + Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"), } } else { tracing::info!("no host pipeline library yet; starting an empty one"); } + // The rejected bytes are let go (a mapped file is unmapped) before the + // empty library is made: nothing reads them any more. + drop(blob); let library = make(&[]).ok()?; Some(Library { library, - _blob: Vec::new(), - added: 0, - stored: HashSet::new(), + _blob: Blob::None, + added: AtomicU64::new(0), + saving: RwLock::new(()), }) } @@ -161,11 +500,7 @@ fn open(device: &ID3D12Device1, blob: Vec) -> Option { /// description holds. pub(crate) fn name(kind: &str, root: &[u8], code: &[&[u8]], state: &str) -> String { let mut h = blake3::Hasher::new(); - for part in [kind.as_bytes(), root] - .into_iter() - .chain(code.iter().copied()) - .chain([state.as_bytes()]) - { + for part in [kind.as_bytes(), root].into_iter().chain(code.iter().copied()).chain([state.as_bytes()]) { h.update(&(part.len() as u64).to_le_bytes()); h.update(part); } @@ -180,53 +515,61 @@ pub(crate) fn pipeline( create: impl FnOnce() -> windows::core::Result, ) -> windows::core::Result { let wide = HSTRING::from(name); - let Some(libraries) = libraries() else { + let Some(library) = library() else { MADE.fetch_add(1, Ordering::Relaxed); return create(); }; - let shard = &libraries[shard_of(name)]; - // A load can be a whole compile under vkd3d-proton, whose library keeps - // no compiled code; do not hold the store/serialise lock across it. The - // host requires only same-name loads to serialise, so those get a lock of - // their own and different pipelines still load in parallel. - let handle = shard - .lock() - .unwrap_or_else(|e| e.into_inner()) - .library - .clone(); - let same = LOADS - .lock() - .unwrap_or_else(|e| e.into_inner()) - .entry(name.to_owned()) - .or_default() - .clone(); - let _same = same.lock().unwrap_or_else(|e| e.into_inner()); - if let Ok(pso) = load(&handle, PCWSTR(wide.as_ptr())) { - LOADED.fetch_add(1, Ordering::Relaxed); - return Ok(pso); - } - // Compiled outside the lock: compiles take up to seconds. - let pso = create()?; - MADE.fetch_add(1, Ordering::Relaxed); - let mut l = shard.lock().unwrap_or_else(|e| e.into_inner()); - if l.stored.insert(name.to_owned()) { - // SAFETY: a live pipeline; a name already stored in an earlier run - // is refused, which leaves the library as it was. - if unsafe { l.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() { - l.added += 1; + let began = std::time::Instant::now(); + let loaded = { + let _all = one_call(); + let _one = same_name(name); + let _call = call("load", name); + load(&library.library, PCWSTR(wide.as_ptr())) + }; + // The load read the library's file (see `trim`). + LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed); + TRIMMED.store(false, Ordering::Relaxed); + let refused = match loaded { + Ok(pso) => { + LOADED.fetch_add(1, Ordering::Relaxed); + crate::host::trail(|| { + let label = LABEL.with(|l| l.borrow().clone()); + format!("pipeline library: loaded {label} in {:.1} ms", began.elapsed().as_secs_f64() * 1e3) + }); + return Ok(pso); } + Err(e) => e, + }; + // Compiled outside any lock: compiles take up to seconds. + let pso = { + let _call = call("make", name); + create()? + }; + MADE.fetch_add(1, Ordering::Relaxed); + crate::host::trail(|| { + let label = LABEL.with(|l| l.borrow().clone()); + format!( + "pipeline library: made {label} in {:.1} ms (the library did not load it: {refused})", + began.elapsed().as_secs_f64() * 1e3 + ) + }); + let _all = one_call(); + let _stores = library.saving.read().unwrap_or_else(|e| e.into_inner()); + let _call = call("store", name); + // SAFETY: a live pipeline; a name already stored (a description that + // differs) is refused, which leaves the library as it was. + if unsafe { library.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() { + library.added.fetch_add(1, Ordering::Relaxed); } Ok(pso) } -/// Writes the shards that gained pipelines since the last save, and the -/// early list if it changed, when `SAVE_EVERY` has passed (or `now`). +/// Writes the library and the early list if pipelines were added since the +/// last save and `SAVE_EVERY` has passed (or `now`). pub(crate) fn save(now: bool) { static LAST: Mutex> = Mutex::new(None); const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20); - let (Some(dir), Some(libraries)) = (DIR.get(), libraries()) else { - return; - }; + let (Some(dir), Some(library)) = (DIR.get(), library()) else { return }; { let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); if !now && last.is_some_and(|t| t.elapsed() < SAVE_EVERY) { @@ -234,74 +577,99 @@ pub(crate) fn save(now: bool) { } *last = Some(std::time::Instant::now()); } - // Serialising and publishing are both inside this lock, so two saves - // cannot interleave and publish an older snapshot over a newer one. - let _saving = SAVING.lock().unwrap_or_else(|e| e.into_inner()); if let Err(e) = std::fs::create_dir_all(dir) { - tracing::warn!(error = %e, "host pipeline library folder not made"); + tracing::warn!(error = %e, "host pipeline library not saved"); return; } - let used_changed = USED_CHANGED.load(Ordering::Relaxed); - let used: Vec = USED - .lock() - .unwrap_or_else(|e| e.into_inner()) - .iter() - .flatten() - .cloned() - .collect(); - let mut saved = 0u32; - let mut total = 0usize; - for (shard, library) in libraries.iter().enumerate() { - let (blob, added) = { - let l = library.lock().unwrap_or_else(|e| e.into_inner()); - if l.added == 0 { - continue; - } - // SAFETY: a buffer of the size the library asks for. - let bytes = unsafe { - let mut bytes = vec![0u8; l.library.GetSerializedSize()]; - l.library.Serialize(&mut bytes).map(|()| bytes) - }; - match bytes { - Ok(bytes) => (bytes, l.added), - Err(e) => { - tracing::warn!(error = %e, shard, "host pipeline library shard not serialised"); - continue; - } - } - }; - match write_atomically(&dir.join(shard_file(shard)), &blob) { - Ok(()) => { - // Cleared only once the bytes are published, by what was - // serialised: a failed write leaves the shard dirty for the - // next save, and a store during the write keeps it dirty. - let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); - l.added = l.added.saturating_sub(added); - saved += 1; - total += blob.len(); + let tmp = dir.join(LIBRARY_FILE).with_extension("tmp"); + // The bytes of the library written to `tmp`; 0 when no pipeline was + // added: the library on disk is then what it was, and only the early + // list is written (a title pipeline first drawn with wrote all 1,352 MB + // of the library again: run 60's second save). + let bytes = { + let _all = one_call(); + // No store between asking the size and writing; loads go on. + let _alone = library.saving.write().unwrap_or_else(|e| e.into_inner()); + let added = library.added.load(Ordering::Relaxed); + if !USED_CHANGED.swap(false, Ordering::Relaxed) && added == 0 { + return; + } + if added == 0 { + 0 + } else { + // SAFETY: a plain query. + let size = unsafe { library.library.GetSerializedSize() }; + let _call = call("serialise", "the whole library"); + if let Err(e) = serialise(&library.library, &tmp, size) { + tracing::warn!(error = %e, "host pipeline library not serialised"); + let _ = std::fs::remove_file(&tmp); + return; } - Err(e) => tracing::warn!(error = %e, shard, "host pipeline library shard not saved"), + library.added.store(0, Ordering::Relaxed); + SAVED.store(size as u64, Ordering::Relaxed); + size } - } - if used_changed || saved > 0 { - match write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes()) { - Ok(()) => USED_CHANGED.store(false, Ordering::Relaxed), - Err(e) => tracing::warn!(error = %e, "early pipeline list not saved"), + }; + let used: Vec = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect(); + let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) }; + if bytes > 0 && library_written.is_ok() { + // In place unless the system refused and the new one waits beside it. + let in_place = !dir.join(NEXT_FILE).exists(); + if in_place && VIEW[0].load(Ordering::Relaxed) != 0 { + REPLACED[1].store(crate::host::now_ms(), Ordering::Relaxed); + REPLACED[0].fetch_add(1, Ordering::Relaxed); } + crate::host::trail(|| { + format!( + "pipeline library: saved {bytes} bytes, {}", + if in_place { "renamed over the library's file" } else { "left beside the library's file for the next start" } + ) + }); } - if saved > 0 { - tracing::info!( - shards = saved, - bytes = total, + let written = library_written + .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes())); + match written { + Ok(()) => tracing::info!( + bytes, early = used.len(), made = MADE.load(Ordering::Relaxed), loaded = LOADED.load(Ordering::Relaxed), started_early = EARLY.load(Ordering::Relaxed), "host pipeline library saved" - ); + ), + Err(e) => tracing::warn!(error = %e, "host pipeline library not saved"), } } +/// Writes the library's `size` serialised bytes to the file `tmp`: through +/// a mapping of that file, so that the bytes are the file's pages and not +/// 1.3 GB more of the process's own memory for the seconds a save takes; +/// through a buffer where the file cannot be mapped (and with +/// `VICTORY_LIBRARY_MAP=0`). +fn serialise(library: &ID3D12PipelineLibrary1, tmp: &std::path::Path, size: usize) -> std::io::Result<()> { + let failed = |e: windows::core::Error| std::io::Error::other(e.to_string()); + if mapped() + && let Some(mut file) = Mapped::create(tmp, size) + { + // SAFETY: a buffer of the size the library asks for. + return unsafe { library.Serialize(file.bytes_mut()) }.map_err(failed); + } + let mut bytes = vec![0u8; size]; + // SAFETY: a buffer of the size the library asks for. + unsafe { library.Serialize(&mut bytes) }.map_err(failed)?; + std::fs::write(tmp, &bytes) +} + +/// Renames the written library `tmp` over the library's file in `dir`. This +/// run may have that file mapped: Windows 11 replaces a mapped file, and +/// the mapping goes on reading the old one for as long as a handle on it +/// is open ([`holds`]; with none, only the pages in memory at that moment +/// stay: the rest read as zeros). Where a system refuses, the new library +/// is left beside it as [`NEXT_FILE`] for the next start. +fn replace_library(dir: &std::path::Path, tmp: &std::path::Path) -> std::io::Result<()> { + std::fs::rename(tmp, dir.join(LIBRARY_FILE)).or_else(|_| std::fs::rename(tmp, dir.join(NEXT_FILE))) +} + /// Writes `bytes` to a temporary file beside `path`, then renames it over /// `path`: a reader never sees a part. fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { @@ -321,11 +689,7 @@ fn used() -> std::sync::MutexGuard<'static, Option>> { .get() .and_then(|d| std::fs::read_to_string(d.join(EARLY_FILE)).ok()) .unwrap_or_default(); - let set: HashSet = listed - .lines() - .filter(|l| !l.is_empty()) - .map(str::to_owned) - .collect(); + let set: HashSet = listed.lines().filter(|l| !l.is_empty()).map(str::to_owned).collect(); tracing::info!(pipelines = set.len(), "title pipelines to start early"); *used = Some(set); } @@ -362,27 +726,116 @@ mod tests { assert_ne!(a, name("graphics", b"root", &[b"vsp", b"s"], "state")); } - #[test] - fn a_pipeline_lands_in_one_shard_and_the_shards_spread() { - let first = name("graphics", b"root", &[b"vs", b"ps"], "state"); - assert_eq!(shard_of(&first), shard_of(&first), "stable across runs"); - let mut seen = [0usize; SHARDS]; - for i in 0..2048u32 { - seen[shard_of(&format!("{i:032x}"))] += 1; - } - assert!(seen.iter().all(|&n| n > 0), "every shard is used: {seen:?}"); - } - #[test] fn a_rejected_blob_gives_an_empty_library() { - let Some(device) = crate::host::host().and_then(|h| h.device.cast::().ok()) - else { + let Some(device) = crate::host::host().and_then(|h| h.device.cast::().ok()) else { return; // no host GPU here }; - let library = - open(&device, b"not a pipeline library".repeat(16)).expect("an empty library"); + let library = open(&device, Blob::Held(b"not a pipeline library".repeat(16))).expect("an empty library"); // SAFETY: a plain query on a live library. assert!(unsafe { library.library.GetSerializedSize() } > 0); - assert!(library._blob.is_empty()); + assert!(matches!(library._blob, Blob::None)); + } + + /// A mapped file reads as the file's bytes, a file written through a + /// mapping holds what was written, and the library's file can be + /// replaced while it is mapped (or the new one waits as the next). + #[test] + fn the_library_file_is_mapped_and_replaced() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(LIBRARY_FILE); + assert!(matches!(Blob::of(dir.path()), Blob::None), "no file yet"); + std::fs::write(&path, b"").unwrap(); + assert!(matches!(Blob::of(dir.path()), Blob::None), "an empty file"); + let old: Vec = (0..200_000u32).map(|i| i as u8).collect(); + std::fs::write(&path, &old).unwrap(); + let blob = Blob::of(dir.path()); + assert!(matches!(blob, Blob::Mapped(_)) || !mapped()); + assert_eq!(blob.bytes(), &old[..]); + // A save while the old file is mapped. + let tmp = path.with_extension("tmp"); + let new: Vec = (0..300_000u32).map(|i| (i * 7) as u8).collect(); + { + let mut file = Mapped::create(&tmp, new.len()).expect("a new file, mapped"); + file.bytes_mut().copy_from_slice(&new); + } + assert_eq!(std::fs::read(&tmp).unwrap(), new); + replace_library(dir.path(), &tmp).unwrap(); + assert!(!tmp.exists()); + // The mapping still reads the old library. + assert_eq!(blob.bytes(), &old[..]); + drop(blob); + // The next start reads the new one, wherever the save left it. + assert_eq!(Blob::of(dir.path()).bytes(), &new[..]); + assert!(!dir.path().join(NEXT_FILE).exists()); + } + + /// The bytes at `at` of the pattern the test below writes. + fn pattern(at: usize, out: &mut [u8]) { + for (i, word) in out.chunks_exact_mut(4).enumerate() { + let v = ((at / 4 + i) as u32).wrapping_mul(2_654_435_761).wrapping_add(1); + word.copy_from_slice(&v.to_le_bytes()); + } + } + + /// A file of `len` bytes (whole MiB) of [`pattern`], written past the + /// system's cache: none of its pages is in memory afterwards. False + /// where the folder's file system does not take such writes. + fn write_uncached(path: &std::path::Path, len: usize) -> bool { + use std::io::Write; + use std::os::windows::fs::OpenOptionsExt; + // FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH + const UNCACHED: u32 = 0x2000_0000 | 0x8000_0000; + const CHUNK: usize = 1 << 20; + let Ok(mut file) = std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .custom_flags(UNCACHED) + .open(path) + else { + return false; + }; + // Such writes want a buffer on a sector boundary. + let mut store = vec![0u8; CHUNK + 4096]; + let start = store.as_ptr().align_offset(4096); + for at in (0..len).step_by(CHUNK) { + let chunk = &mut store[start..start + CHUNK]; + pattern(at, chunk); + if file.write_all(chunk).is_err() { + return false; + } + } + true + } + + /// The device loss of runs 72, 73 and 82: the library's file is + /// replaced while it is mapped, and pages of the mapping that were not + /// in memory then are read afterwards (in the runs: pages the trim let + /// go and Windows gave to something else). With the file's handle kept + /// open they still read as the old file. (With it closed, as before, + /// all but the first few read as zeros on the PC this was found on.) + #[test] + fn a_replaced_library_file_still_reads_from_the_disk() { + const LEN: usize = 8 << 20; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(LIBRARY_FILE); + if !write_uncached(&path, LEN) { + return; // no uncached writes here: nothing to show + } + let mapped = Mapped::open_holding(&path, true).expect("the file, mapped"); + // A save: the new library, renamed over the mapped one. + let tmp = path.with_extension("tmp"); + { + let mut file = Mapped::create(&tmp, LEN).expect("a new file, mapped"); + file.bytes_mut().fill(0xEE); + } + replace_library(dir.path(), &tmp).unwrap(); + // Every page of the old mapping, read for the first time now. + let mut expected = vec![0u8; 4096]; + for (page, bytes) in mapped.bytes().chunks(4096).enumerate() { + pattern(page * 4096, &mut expected); + assert!(bytes == &expected[..], "page {page} of the replaced library no longer reads as the old file"); + } } } diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index ffce60d..9862446 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -1,61 +1,33 @@ //! Host pipelines are made by workers, not by the title thread that first //! records a draw with them. Translating a shader and the host driver's //! compile take from milliseconds to seconds each (structurisation of the -//! biggest compute programs ~0.4 s, some driver compiles 3.4 s), and Grand -//! Theft Auto VI's first world frame wants over 1,200 new pipelines: made +//! biggest compute programs ~0.4 s, some driver compiles 3.4 s), and +//! the title's first world frame wants over 1,200 new pipelines: made //! on its recording threads, that frame took more than 30 s and the //! title's GPU watchdog ended the run (decision 0007, "Pipelines made off //! the title's threads"). //! -//! A first use queues the pipeline on a repeat-demand priority queue and -//! waits for it within a budget per frame, so the cheap ones (menus, -//! one-off passes such as a colour-grading bake) are there at once as before; -//! pipelines demanded again by recurring draws/dispatches jump ahead of -//! single-hit entries (with non-mesh tie-breaking and bounded anti-starvation -//! fairness) and ahead of speculative early pre-warms; past the budget a -//! draw or dispatch whose pipeline is not ready is dropped, as an -//! untranslated one is. +//! A first use queues the pipeline and waits for it within a budget per +//! frame, so the cheap ones (menus, one-off passes such as a colour-grading +//! bake) are there at once as before; past the budget a draw or dispatch +//! whose pipeline is not ready is dropped, as an untranslated one is. //! -//! shortcut: the budget (half a second of waiting per title frame, -//! `VICTORY_PIPELINE_WAIT_MS`) is a guess; a pass the title runs only once and whose pipeline takes longer -//! is lost. +//! The default budget is half a second per title frame. A pass the title +//! runs only once and whose pipeline takes longer is lost. -use std::collections::{BinaryHeap, VecDeque}; -use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}; +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; use super::Shader; use super::host::{GraphicsState, HostPipeline}; -const UNQUEUED: u8 = 0; -const EARLY: u8 = 1; -const DEMAND: u8 = 2; -/// Highest priority bucket (`hits >= 256`); caps duplicate heap pushes per item. -const MAX_TIER: u8 = 10; -/// Maximum consecutive higher-tier (`tier >= 2`) pops before serving one oldest -/// waiting demand entry. -const FAIR_STRIDE: u32 = 16; - -fn demand_tier(hits: u32) -> u8 { - match hits { - 0 => 0, - 1..=3 => hits as u8, - n => (33 - n.leading_zeros()).min(u32::from(MAX_TIER)) as u8, - } -} - /// What a host pipeline is made from, and the host pipeline once made. pub(crate) struct Pending { shaders: Vec>, pub(crate) graphics: Option>, - non_mesh: bool, - lane: AtomicU8, - hits: AtomicU32, - tier_queued: AtomicU8, - counted: AtomicBool, - in_fair: AtomicBool, - started: AtomicBool, + queue_state: AtomicU8, made: OnceLock>, /// What identifies it across runs (shader containers and state), and /// whether a draw or dispatch has requested it yet. @@ -71,52 +43,22 @@ unsafe impl Sync for Pending {} impl Pending { pub(crate) fn new(shaders: Vec>, graphics: Option>) -> Pending { - let non_mesh = !shaders.iter().any(|s| s.stage == "mesh"); - Self::with_non_mesh(shaders, graphics, non_mesh) - } - - fn with_non_mesh( - shaders: Vec>, - graphics: Option>, - non_mesh: bool, - ) -> Pending { let mut key = blake3::Hasher::new(); for s in &shaders { key.update(s.stage.as_bytes()); key.update(s.hash.as_bytes()); } - key.update( - graphics - .as_ref() - .map(|g| g.describe()) - .unwrap_or_default() - .as_bytes(), - ); + key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); Pending { shaders, graphics, - non_mesh, - lane: AtomicU8::new(UNQUEUED), - hits: AtomicU32::new(0), - tier_queued: AtomicU8::new(0), - counted: AtomicBool::new(false), - in_fair: AtomicBool::new(false), - started: AtomicBool::new(false), + queue_state: AtomicU8::new(NOT_QUEUED), made: OnceLock::new(), key: key.finalize().to_hex()[..32].to_owned(), used: AtomicBool::new(false), } } - #[cfg(test)] - fn is_queued(&self) -> bool { - self.lane.load(Ordering::Relaxed) != UNQUEUED - } - - fn claim(&self) -> bool { - !self.started.swap(true, Ordering::AcqRel) - } - fn make(&self) { self.made .get_or_init(|| HostPipeline::new(&self.shaders, self.graphics.as_deref())); @@ -149,212 +91,20 @@ pub(crate) fn missing(p: &Pending) -> Option { } } -struct WorkItem { - tier: u8, - non_mesh: bool, - seq: u64, - pending: Arc, -} - -impl Ord for WorkItem { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.tier - .cmp(&other.tier) - .then_with(|| self.non_mesh.cmp(&other.non_mesh)) - .then_with(|| other.seq.cmp(&self.seq)) - } -} - -impl PartialOrd for WorkItem { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Eq for WorkItem {} - -impl PartialEq for WorkItem { - fn eq(&self, other: &Self) -> bool { - self.cmp(other) == std::cmp::Ordering::Equal - } -} - -struct Queues { - next_seq: u64, - high_streak: u32, - demand: BinaryHeap, - fair_fifo: VecDeque>, - early: VecDeque>, -} - -impl Queues { - const fn new() -> Self { - Self { - next_seq: 0, - high_streak: 0, - demand: BinaryHeap::new(), - fair_fifo: VecDeque::new(), - early: VecDeque::new(), - } - } - - /// Pops the highest-priority unclaimed pipeline: repeat-demanded entries - /// (with non-mesh, oldest-queued tie-break) ahead of 1-hit demand entries, - /// interleaving an oldest waiting demand entry after `FAIR_STRIDE` high-tier - /// pops so 1-hit work cannot permanently starve, and draining `early` last. - fn pop_claimed(&mut self) -> Option> { - while self - .fair_fifo - .front() - .is_some_and(|p| p.started.load(Ordering::Acquire)) - { - self.fair_fifo.pop_front(); - } - if self.high_streak >= FAIR_STRIDE && !self.fair_fifo.is_empty() { - while let Some(p) = self.fair_fifo.pop_front() { - if p.claim() { - self.high_streak = 0; - return Some(p); - } - } - } - while let Some(item) = self.demand.pop() { - if item.pending.claim() { - if item.tier >= 2 { - self.high_streak += 1; - } else { - self.high_streak = 0; - } - return Some(item.pending); - } - } - self.high_streak = 0; - while let Some(p) = self.early.pop_front() { - if p.claim() { - return Some(p); - } - } - None - } -} - -struct WorkQueue { - state: Mutex, - ready: Condvar, - workers_alive: AtomicBool, -} - -impl WorkQueue { - fn new(workers_alive: bool) -> Self { - Self { - state: Mutex::new(Queues::new()), - ready: Condvar::new(), - workers_alive: AtomicBool::new(workers_alive), - } - } - - fn make_inline(p: &Pending, waiting: &AtomicU64, peak: &AtomicU64) { - if p.claim() { - if !p.counted.swap(true, Ordering::Relaxed) { - peak.fetch_max( - waiting.fetch_add(1, Ordering::Relaxed) + 1, - Ordering::Relaxed, - ); - } - p.make(); - if waiting.fetch_sub(1, Ordering::Relaxed) == 1 { - drained(); - } - } - } - - fn push_demand(&self, p: Arc, tier: u8, waiting: &AtomicU64, peak: &AtomicU64) { - if !self.workers_alive.load(Ordering::Acquire) { - Self::make_inline(&p, waiting, peak); - return; - } - let mut queues = self.state.lock().unwrap_or_else(|e| e.into_inner()); - if p.started.load(Ordering::Acquire) { - return; - } - if !p.counted.swap(true, Ordering::Relaxed) { - peak.fetch_max( - waiting.fetch_add(1, Ordering::Relaxed) + 1, - Ordering::Relaxed, - ); - } - let seq = queues.next_seq; - queues.next_seq = queues.next_seq.wrapping_add(1); - if queues.demand.is_empty() && tier <= 1 { - queues.high_streak = 0; - } - if !p.in_fair.swap(true, Ordering::Relaxed) { - queues.fair_fifo.push_back(p.clone()); - } - queues.demand.push(WorkItem { - tier, - non_mesh: p.non_mesh, - seq, - pending: p, - }); - drop(queues); - self.ready.notify_one(); - } - - fn push_early(&self, p: Arc, waiting: &AtomicU64, peak: &AtomicU64) { - if !self.workers_alive.load(Ordering::Acquire) { - Self::make_inline(&p, waiting, peak); - return; - } - let mut queues = self.state.lock().unwrap_or_else(|e| e.into_inner()); - if p.started.load(Ordering::Acquire) { - return; - } - if !p.counted.swap(true, Ordering::Relaxed) { - peak.fetch_max( - waiting.fetch_add(1, Ordering::Relaxed) + 1, - Ordering::Relaxed, - ); - } - queues.early.push_back(p); - drop(queues); - self.ready.notify_one(); - } - - fn recv(&self) -> Arc { - let mut queues = self.state.lock().unwrap_or_else(|e| e.into_inner()); - loop { - if let Some(p) = queues.pop_claimed() { - return p; - } - queues = self.ready.wait(queues).unwrap_or_else(|e| e.into_inner()); - } - } - - #[cfg(test)] - fn try_pop(&self) -> Option> { - self.state - .lock() - .unwrap_or_else(|e| e.into_inner()) - .pop_claimed() - } -} - /// Signalled whenever a worker has made a pipeline. static DONE: (Mutex<()>, Condvar) = (Mutex::new(()), Condvar::new()); -/// Waiting allowed per title frame, over all threads: 500 ms unless -/// `VICTORY_PIPELINE_WAIT_MS` says otherwise (0: never wait, a draw whose -/// pipeline is not made yet is dropped until it is; one-off passes such as -/// a colour-grading bake may then be lost). -fn budget() -> Duration { - static MS: std::sync::OnceLock = std::sync::OnceLock::new(); - Duration::from_millis(*MS.get_or_init(|| { - std::env::var("VICTORY_PIPELINE_WAIT_MS") +/// Waiting allowed per title frame, over all threads. +fn wait_budget() -> Duration { + static BUDGET: OnceLock = OnceLock::new(); + *BUDGET.get_or_init(|| { + let millis = std::env::var("VICTORY_PIPELINE_WAIT_MS") .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(500) - })) + .and_then(|value| value.trim().parse::().ok()) + .unwrap_or(500); + tracing::info!(millis, "host pipeline wait budget per frame"); + Duration::from_millis(millis) + }) } /// Pipelines queued and not made yet. @@ -366,8 +116,7 @@ pub(crate) fn waiting() -> u64 { } /// The host pipeline if it is made (or is made within the frame's budget); -/// queues it on first use, promotes queued early pipelines, and upgrades -/// priority on repeat demand. +/// queues it on first use. pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { // A still-pending pipeline was requested by the title too. Prewarm it // on the next launch, even if this run never got to use it. @@ -375,81 +124,62 @@ pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { super::library::note_used(&p.key); } if p.made.get().is_none() { - start(p, true); + start(p, REQUESTED); wait(p, crate::frame::current()); } p.made.get()?.as_ref() } -/// Queues `p` for the workers on the demand or early lane (and promotes -/// unstarted early pipelines to demand without double-counting `WAITING`). -fn start(p: &Arc, is_demand: bool) { - enqueue_on(p, is_demand, &WAITING, &PEAK, work_queue()); -} - -fn bump_hit(hits: &AtomicU32) -> u32 { - match hits.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1)) { - Ok(prev) => prev + 1, - Err(max) => max, - } -} - -fn enqueue_on( - p: &Arc, - is_demand: bool, - waiting: &AtomicU64, - peak: &AtomicU64, - queue: &WorkQueue, -) { - if !is_demand { - if p.lane - .compare_exchange(UNQUEUED, EARLY, Ordering::AcqRel, Ordering::Acquire) - .is_ok() - { - queue.push_early(p.clone(), waiting, peak); - } - return; - } - - if p.started.load(Ordering::Acquire) { - return; - } - let _ = p - .lane - .compare_exchange(UNQUEUED, DEMAND, Ordering::AcqRel, Ordering::Acquire) - .or_else(|_| { - p.lane - .compare_exchange(EARLY, DEMAND, Ordering::AcqRel, Ordering::Acquire) - }); - if p.started.load(Ordering::Acquire) { - return; - } - let hits = bump_hit(&p.hits); - let tier = demand_tier(hits); - let prev = p.tier_queued.fetch_max(tier, Ordering::AcqRel); - if prev < tier { - queue.push_demand(p.clone(), tier, waiting, peak); - } +/// Makes `p` on this thread if it is not made yet (waiting for a worker +/// that is making it); whether it has a host pipeline. +pub(crate) fn now(p: &Arc) -> bool { + p.make(); + p.made.get().is_some_and(|made| made.is_some()) } -/// At the title's creation of a pipeline: starts it at once on the lower-priority -/// lane if an earlier run drew with it (during loading, so the world's first -/// frames find it without delaying live draws). +/// At the title's creation of a pipeline: starts it at once if an earlier +/// run drew with it (during loading, so the world's first frames find it). pub(crate) fn early(p: &Arc) { if !p.shaders.is_empty() && super::library::wanted_early(&p.key) { super::library::EARLY.fetch_add(1, Ordering::Relaxed); - start(p, false); + start(p, EARLY); } } +/// Whether the frame's budget is one for all threads together: a thread +/// that waits takes what is left of it and gives back what it did not +/// use. Counted only when a wait had ended, the budget was one per thread: +/// each of the title's five recording threads began its first wait of a +/// frame with nothing counted yet and waited the whole half second, 2.5 s +/// of waiting in every frame in which pipelines were being made (runs +/// 34-49: "2504 ms waiting for pipelines" in each such frame). +/// On by default; `VICTORY_PIPELINE_WAIT_SHARED=0` counts as before. +fn shared_budget() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_SHARED").is_none_or(|v| v != "0")) +} + /// Waits for `p` while frame `frame` has budget left. fn wait(p: &Pending, frame: u64) { - static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); - static WAITED_US: AtomicU64 = AtomicU64::new(0); - if FRAME.swap(frame, Ordering::Relaxed) != frame { - WAITED_US.store(0, Ordering::Relaxed); + let budget = wait_budget(); + if budget.is_zero() { + return; } - let left = budget().saturating_sub(Duration::from_micros(WAITED_US.load(Ordering::Relaxed))); + // The frame the budget belongs to, and what was waited of it (or is + // taken by a thread waiting now). + static SPENT: Mutex<(u64, Duration)> = Mutex::new((u64::MAX, Duration::ZERO)); + let shared = shared_budget(); + let left = { + let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner()); + if spent.0 != frame { + *spent = (frame, Duration::ZERO); + } + let left = budget.saturating_sub(spent.1); + if shared { + spent.1 += left; + } + left + }; if left.is_zero() { return; } @@ -461,53 +191,125 @@ fn wait(p: &Pending, frame: u64) { if rest.is_zero() { break; } - held = done - .wait_timeout(held, rest) - .unwrap_or_else(|e| e.into_inner()) - .0; + held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0; + } + drop(held); + let waited = started.elapsed().min(left); + { + let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner()); + // A frame that began meanwhile has its own budget. + if spent.0 == frame { + if shared { + spent.1 = spent.1.saturating_sub(left - waited); + } else { + spent.1 += waited; + } + } } - WAITED_US.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::add( + crate::copystat::C::PipelineWaitUs, + started.elapsed().as_micros() as u64, + ); +} + +const NOT_QUEUED: u8 = 0; +const EARLY: u8 = 1; +const REQUESTED: u8 = 2; +const MAKING: u8 = 3; + +struct Queue { + early: VecDeque>, + requested: VecDeque>, } -/// Stack of each pipeline worker: room for the driver's shader compiler, -/// which runs on it (reserved address space; committed only as used). -const PIPELINE_STACK: usize = 64 << 20; - -/// Pipeline workers: half the logical processors, 2 to 8, unless -/// `VICTORY_PIPELINE_WORKERS` names a count (1 to 64). Driver compiles of the -/// world's largest programs bound a first run with an empty pipeline library. -fn worker_count(asked: Option<&str>, processors: usize) -> usize { - asked - .and_then(|v| v.trim().parse::().ok()) - .map_or((processors / 2).clamp(2, 8), |n| n.clamp(1, 64)) +impl Queue { + const fn new() -> Self { + Self { + early: VecDeque::new(), + requested: VecDeque::new(), + } + } + + /// Queues an unrequested pipeline or promotes one queued at creation. + /// Returns whether it is new to the queue, or `None` if nothing changed. + fn push(&mut self, p: &Arc, priority: u8) -> Option { + let prev = p.queue_state.load(Ordering::Relaxed); + if prev >= priority { + return None; + } + p.queue_state.store(priority, Ordering::Relaxed); + if priority == REQUESTED { + self.requested.push_back(p.clone()); + } else { + self.early.push_back(p.clone()); + } + Some(prev == NOT_QUEUED) + } + + fn pop(&mut self) -> Option> { + let p = self.requested.pop_front().or_else(|| { + // An early entry can have been promoted and claimed already. + std::iter::from_fn(|| self.early.pop_front()) + .find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY) + })?; + p.queue_state.store(MAKING, Ordering::Relaxed); + Some(p) + } } -/// Shared priority queue and workers, started on first use. -fn work_queue() -> &'static WorkQueue { - static QUEUE: OnceLock> = OnceLock::new(); - QUEUE.get_or_init(|| { - let queue = Arc::new(WorkQueue::new(false)); - let workers = worker_count( - std::env::var("VICTORY_PIPELINE_WORKERS").ok().as_deref(), - std::thread::available_parallelism().map_or(4, |n| n.get()), - ); - tracing::info!(workers, "host pipeline workers"); - let mut alive = false; +static QUEUE: Mutex = Mutex::new(Queue::new()); +static AVAILABLE: Condvar = Condvar::new(); + +/// Start or promote work for a draw without waiting behind the entire early +/// list. Queue changes and worker claims happen under the same lock. +fn start(p: &Arc, priority: u8) { + if p.queue_state.load(Ordering::Relaxed) >= priority { + return; + } + if !workers() { + if p.queue_state.swap(MAKING, Ordering::Relaxed) == NOT_QUEUED { + p.make(); + } + return; + } + let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(new) = queue.push(p, priority) { + if new { + PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed); + } + AVAILABLE.notify_one(); + } +} + +fn next() -> Arc { + let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(p) = queue.pop() { + return p; + } + queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner()); + } +} + +/// Starts the workers (half the logical processors, 2 to 8) on first use. +fn workers() -> bool { + static RUNNING: OnceLock = OnceLock::new(); + *RUNNING.get_or_init(|| { + let mut running = false; + let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8)); for i in 0..workers { - let worker_queue = queue.clone(); let spawned = std::thread::Builder::new() .name(format!("victory-pipelines-{i}")) - // The driver compiles pipelines on this thread, recursively: - // NVIDIA's compiler (nvgpucomp64) overflowed the default 2 MB - // on a world compute program and refused it as out of memory. - .stack_size(PIPELINE_STACK) - .spawn(move || { - // At the title's own priority: below it, the world's busy - // threads starved the workers, and draws stayed dropped - // until their pipelines existed. + .spawn(|| { + // Below the title's own threads (loading, recording). + // SAFETY: a plain call on our own thread. + unsafe { + use windows::Win32::System::Threading::*; + let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + } loop { - let p = worker_queue.recv(); - p.make(); + next().make(); if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 { drained(); } else { @@ -515,13 +317,13 @@ fn work_queue() -> &'static WorkQueue { } } }); - match spawned { - Ok(_) => alive = true, - Err(e) => tracing::warn!(error = %e, "no pipeline worker"), + if let Err(e) = spawned { + tracing::warn!(error = %e, "no pipeline worker"); + } else { + running = true; } } - queue.workers_alive.store(alive, Ordering::Release); - queue + running }) } @@ -547,24 +349,13 @@ fn drained() { mod tests { use super::*; - #[test] - fn worker_count_takes_the_switch_within_bounds() { - assert_eq!(worker_count(None, 20), 8); - assert_eq!(worker_count(None, 2), 2); - assert_eq!(worker_count(Some("16"), 20), 16); - assert_eq!(worker_count(Some(" 3 "), 20), 3); - assert_eq!(worker_count(Some("0"), 20), 1); - assert_eq!(worker_count(Some("1000"), 20), 64); - assert_eq!(worker_count(Some("many"), 12), 6); - } - /// A first use queues the pipeline and, within the budget, gets the /// worker's answer (here: no host pipeline for no shaders). #[test] fn first_use_is_made_by_a_worker() { let p = Arc::new(Pending::new(Vec::new(), None)); assert!(ready(&p).is_none()); - assert!(p.is_queued()); + assert_ne!(p.queue_state.load(Ordering::Relaxed), NOT_QUEUED); let started = Instant::now(); while p.made.get().is_none() && started.elapsed() < Duration::from_secs(10) { std::thread::yield_now(); @@ -576,9 +367,8 @@ mod tests { fn pending_pipeline_is_recorded_for_the_next_launch() { let mut p = Pending::new(Vec::new(), None); p.key = "pending-pipeline-test".to_owned(); - // A worker already has the job: ready() does not requeue it, just - // records the request and waits out the frame's budget. - p.started.store(true, Ordering::Relaxed); + // Simulate a worker that has taken the job but cannot finish it yet. + p.queue_state.store(MAKING, Ordering::Relaxed); let p = Arc::new(p); assert!(!super::super::library::wanted_early(&p.key)); @@ -588,149 +378,22 @@ mod tests { } #[test] - fn priority_queue_runs_ready_and_promoted_before_early() { - let q = WorkQueue::new(true); - let waiting = AtomicU64::new(0); - let peak = AtomicU64::new(0); - - let e1 = Arc::new(Pending::new(Vec::new(), None)); - let e2 = Arc::new(Pending::new(Vec::new(), None)); - let e3 = Arc::new(Pending::new(Vec::new(), None)); - let d1 = Arc::new(Pending::new(Vec::new(), None)); - - enqueue_on(&e1, false, &waiting, &peak, &q); - enqueue_on(&e2, false, &waiting, &peak, &q); - enqueue_on(&e3, false, &waiting, &peak, &q); - assert_eq!(waiting.load(Ordering::Relaxed), 3); - - // Promoting an unstarted early pipeline pushes it onto demand without double-counting. - enqueue_on(&e2, true, &waiting, &peak, &q); - assert_eq!(waiting.load(Ordering::Relaxed), 3); - - // A direct demand pipeline queues ahead of remaining early pipelines too. - enqueue_on(&d1, true, &waiting, &peak, &q); - assert_eq!(waiting.load(Ordering::Relaxed), 4); - assert_eq!(peak.load(Ordering::Relaxed), 4); - - let pop_ptr = || q.try_pop().map(|p| Arc::as_ptr(&p)); - assert_eq!(pop_ptr(), Some(Arc::as_ptr(&e2))); - assert_eq!(pop_ptr(), Some(Arc::as_ptr(&d1))); - assert_eq!(pop_ptr(), Some(Arc::as_ptr(&e1))); - assert_eq!(pop_ptr(), Some(Arc::as_ptr(&e3))); - assert_eq!( - pop_ptr(), - None, - "promoted duplicate in early lane must be skipped" - ); - - // Re-requesting an already claimed pipeline does not re-queue it. - enqueue_on(&e2, true, &waiting, &peak, &q); - assert_eq!(waiting.load(Ordering::Relaxed), 4); - assert!(q.try_pop().is_none()); - } - - #[test] - fn repeated_demand_jumps_ahead_of_hundreds_of_single_hit_pipelines() { - let q = WorkQueue::new(true); - let waiting = AtomicU64::new(0); - let peak = AtomicU64::new(0); - - let one_hit: Vec<_> = (0..500) - .map(|i| Arc::new(Pending::with_non_mesh(Vec::new(), None, i % 2 == 0))) - .collect(); - for p in &one_hit { - enqueue_on(p, true, &waiting, &peak, &q); - } - let hot = Arc::new(Pending::with_non_mesh(Vec::new(), None, false)); - let hotter = Arc::new(Pending::with_non_mesh(Vec::new(), None, false)); - enqueue_on(&hot, true, &waiting, &peak, &q); - enqueue_on(&hot, true, &waiting, &peak, &q); - for _ in 0..4 { - enqueue_on(&hotter, true, &waiting, &peak, &q); - } - assert_eq!(waiting.load(Ordering::Relaxed), 502); - - assert_eq!( - q.try_pop().map(|p| Arc::as_ptr(&p)), - Some(Arc::as_ptr(&hotter)) - ); - assert_eq!( - q.try_pop().map(|p| Arc::as_ptr(&p)), - Some(Arc::as_ptr(&hot)) - ); - - let mut drained_single = 0usize; - while let Some(p) = q.try_pop() { - assert_ne!(Arc::as_ptr(&p), Arc::as_ptr(&hot)); - assert_ne!(Arc::as_ptr(&p), Arc::as_ptr(&hotter)); - drained_single += 1; - } - assert_eq!( - drained_single, 500, - "every 1-hit pipeline must still complete" - ); - } - - #[test] - fn tie_breaks_favor_non_mesh_and_fair_stride_prevents_starvation() { - let q = WorkQueue::new(true); - let waiting = AtomicU64::new(0); - let peak = AtomicU64::new(0); - - let mesh_a = Arc::new(Pending::with_non_mesh(Vec::new(), None, false)); - let mesh_b = Arc::new(Pending::with_non_mesh(Vec::new(), None, false)); - let compute_a = Arc::new(Pending::with_non_mesh(Vec::new(), None, true)); - let pixel_b = Arc::new(Pending::with_non_mesh(Vec::new(), None, true)); - - enqueue_on(&mesh_a, true, &waiting, &peak, &q); - enqueue_on(&mesh_b, true, &waiting, &peak, &q); - enqueue_on(&compute_a, true, &waiting, &peak, &q); - enqueue_on(&pixel_b, true, &waiting, &peak, &q); - - assert_eq!( - q.try_pop().map(|p| Arc::as_ptr(&p)), - Some(Arc::as_ptr(&compute_a)) - ); - assert_eq!( - q.try_pop().map(|p| Arc::as_ptr(&p)), - Some(Arc::as_ptr(&pixel_b)) - ); - assert_eq!( - q.try_pop().map(|p| Arc::as_ptr(&p)), - Some(Arc::as_ptr(&mesh_a)) - ); - assert_eq!( - q.try_pop().map(|p| Arc::as_ptr(&p)), - Some(Arc::as_ptr(&mesh_b)) - ); - assert!(q.try_pop().is_none()); - - // Anti-starvation: after `FAIR_STRIDE` consecutive high-tier pops, one oldest - // 1-hit item is served instead of starving forever under continuous repeat demand. - let old_one_hit = Arc::new(Pending::with_non_mesh(Vec::new(), None, false)); - enqueue_on(&old_one_hit, true, &waiting, &peak, &q); - let hot: Vec<_> = (0..=FAIR_STRIDE as usize) - .map(|_| { - let p = Arc::new(Pending::with_non_mesh(Vec::new(), None, true)); - enqueue_on(&p, true, &waiting, &peak, &q); - enqueue_on(&p, true, &waiting, &peak, &q); - p - }) - .collect(); - - for _ in 0..FAIR_STRIDE { - let popped = q.try_pop().expect("high-tier pop"); - assert_ne!(Arc::as_ptr(&popped), Arc::as_ptr(&old_one_hit)); - } - assert_eq!( - q.try_pop().map(|p| Arc::as_ptr(&p)), - Some(Arc::as_ptr(&old_one_hit)), - "oldest 1-hit pipeline must make forward progress after FAIR_STRIDE high pops" - ); - assert_eq!( - q.try_pop().map(|p| Arc::as_ptr(&p)), - Some(Arc::as_ptr(&hot[FAIR_STRIDE as usize])) - ); - assert!(q.try_pop().is_none()); + fn draws_promote_early_pipelines_without_claiming_them_twice() { + let earlier = Arc::new(Pending::new(Vec::new(), None)); + let promoted = Arc::new(Pending::new(Vec::new(), None)); + let requested = Arc::new(Pending::new(Vec::new(), None)); + let mut queue = Queue::new(); + + assert_eq!(queue.push(&earlier, EARLY), Some(true)); + assert_eq!(queue.push(&promoted, EARLY), Some(true)); + assert_eq!(queue.push(&requested, REQUESTED), Some(true)); + assert_eq!(queue.push(&promoted, REQUESTED), Some(false)); + assert_eq!(queue.push(&promoted, REQUESTED), None); + + assert!(Arc::ptr_eq(&queue.pop().unwrap(), &requested)); + assert!(Arc::ptr_eq(&queue.pop().unwrap(), &promoted)); + assert_eq!(queue.push(&promoted, REQUESTED), None); + assert!(Arc::ptr_eq(&queue.pop().unwrap(), &earlier)); + assert!(queue.pop().is_none()); } } diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index 39ff44b..3f73ee7 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -1,6 +1,6 @@ //! 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 +//! the hardware adds the fourth at `v0 + v2 - v1` (the title'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. @@ -11,20 +11,20 @@ //! [`components`] does not know keep the first vertex's value, and so do //! components past the end of the vertex (an element that reaches into the //! next one, which the layout allows). +//! +//! A pipeline the title makes for rectangles completes them on the GPU +//! instead, in a geometry stage (`victory_shader::emit::rect_list_gs`): +//! from the vertex shader's outputs, whichever vertex the corner is, for +//! direct, indexed and indirect draws alike. This expansion is what is +//! left for a pipeline that could not get that stage. /// 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). pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: &[(u32, u32)]) { - if stride == 0 { - return; - } - let (Some(in_rect), Some(out_rect)) = (stride.checked_mul(3), stride.checked_mul(6)) else { - return; - }; for (rect, out) in src - .chunks_exact(in_rect) - .zip(dst.chunks_exact_mut(out_rect)) + .chunks_exact(3 * stride) + .zip(dst.chunks_exact_mut(6 * stride)) { let v = |i: usize| &rect[i * stride..(i + 1) * stride]; for (slot, i) in [0, 1, 2, 0, 2].into_iter().enumerate() { @@ -147,12 +147,10 @@ fn f32_to_half(v: f32) -> u16 { let m = q + u32::from(r > halfway || (r == halfway && (q & 1) != 0)); return sign | m as u16; } - // Rounded to nearest, halfway cases to even (the retained bit decides); - // a carry out of the mantissa is added into the exponent (`2 - 2^-12` - // is 2.0); at most it reaches infinity, 0x7c00. + // Rounded to nearest: a carry out of the mantissa is added into the + // exponent (`2 - 2^-12` is 2.0); at most it reaches infinity, 0x7c00. let half = (exp as u32) << 10; - let retained = (man >> 13) & 1; - sign | (half + ((man + 0x0fff + retained) >> 13)) as u16 + sign | (half + ((man + 0x1000) >> 13)) as u16 } #[cfg(test)] @@ -206,16 +204,6 @@ mod tests { assert_eq!(dst[10..], 0x4000_u16.to_le_bytes()); } - /// Halfway between two halves, the even one: 1 + 2^-11 lies between - /// 0x3c00 and 0x3c01, 1 + 3 * 2^-11 between 0x3c01 and 0x3c02. - #[test] - fn half_midpoints_round_to_even() { - assert_eq!(f32_to_half(1.0 + 2f32.powi(-11)), 0x3c00); - assert_eq!(f32_to_half(1.0 + 3.0 * 2f32.powi(-11)), 0x3c02); - // Just past a midpoint still rounds up. - assert_eq!(f32_to_half(1.0 + 2f32.powi(-11) + 2f32.powi(-20)), 0x3c01); - } - /// An element that reaches past the stride (float4 at 4 in 8-byte /// vertices, RGBA8 at the stride itself): the components inside get /// the fourth corner, the rest keep the first vertex's bytes. The old @@ -246,83 +234,4 @@ mod tests { assert_eq!(f32_to_half(1.5), 0x3e00); assert_eq!(half_to_f32(0x0001), 2f32.powi(-24)); } - - #[test] - fn zero_or_overflowing_stride_is_ignored_without_panicking() { - let mut dst = [0xAAu8; 16]; - expand_rects(&[1, 2, 3], &mut dst, 0, &[(0, 16)]); - assert_eq!(dst, [0xAAu8; 16]); - expand_rects(&[1, 2, 3], &mut dst, usize::MAX / 2, &[(0, 16)]); - assert_eq!(dst, [0xAAu8; 16]); - } - - #[test] - fn unorm16_unorm8_clamping_and_unknown_formats_expand_correctly() { - // Vertex layout (12 bytes): - // 0..4: R16G16_UNORM (format 35) - // 4..8: R8G8B8A8_UNORM (format 28) — tests clamping below 0 and above 1 - // 8..12: unknown format (999) — must keep v0's bytes verbatim - let v = |u0: u16, u1: u16, c: [u8; 4], raw: [u8; 4]| { - let mut b = Vec::with_capacity(12); - b.extend(u0.to_le_bytes()); - b.extend(u1.to_le_bytes()); - b.extend(c); - b.extend(raw); - b - }; - let src = [ - v( - 10_000, - 50_000, - [10, 200, 100, 255], - [0xDE, 0xAD, 0xBE, 0xEF], - ), - v(20_000, 10_000, [100, 50, 100, 255], [1, 2, 3, 4]), - v(30_000, 20_000, [20, 200, 100, 255], [5, 6, 7, 8]), - ] - .concat(); - let mut dst = vec![0u8; 6 * 12]; - expand_rects(&src, &mut dst, 12, &[(0, 35), (4, 28), (8, 999)]); - let fourth = &dst[60..72]; - // u0: 10000 + 30000 - 20000 = 20000; u1: 50000 + 20000 - 10000 = 60000 - assert_eq!(u16::from_le_bytes([fourth[0], fourth[1]]), 20_000); - assert_eq!(u16::from_le_bytes([fourth[2], fourth[3]]), 60_000); - // c0: 10 + 20 - 100 -> clamped to 0; c1: 200 + 200 - 50 -> clamped to 255 - assert_eq!(&fourth[4..8], &[0, 255, 100, 255]); - // Unknown format keeps v0 bytes - assert_eq!(&fourth[8..12], &[0xDE, 0xAD, 0xBE, 0xEF]); - } - - #[test] - fn multiple_rectangles_and_f32_f16_vector_formats_expand_in_sequence() { - // Two rectangles of R32G32B32_FLOAT (format 6, 12 bytes) + R16G16_FLOAT (format 34, 4 bytes) = 16 bytes - let v = |p: [f32; 3], uv: [f32; 2]| { - let mut b = Vec::with_capacity(16); - for x in p { - b.extend(x.to_le_bytes()); - } - for x in uv { - b.extend(f32_to_half(x).to_le_bytes()); - } - b - }; - let src = [ - // Rect 0 - v([0.0, 1.0, 0.5], [0.0, 0.0]), - v([0.0, 0.0, 0.5], [0.0, 1.0]), - v([2.0, 0.0, 0.5], [1.0, 1.0]), - // Rect 1 - v([10.0, 20.0, 1.0], [0.25, 0.5]), - v([10.0, 10.0, 1.0], [0.25, 1.0]), - v([14.0, 10.0, 1.0], [0.75, 1.0]), - ] - .concat(); - let mut dst = vec![0u8; 12 * 16]; - expand_rects(&src, &mut dst, 16, &[(0, 6), (12, 34)]); - assert_eq!(&dst[5 * 16..6 * 16], &v([2.0, 1.0, 0.5], [1.0, 0.0])[..]); - assert_eq!( - &dst[11 * 16..12 * 16], - &v([14.0, 20.0, 1.0], [0.75, 0.5])[..] - ); - } } diff --git a/crates/victory-gpu/src/profile.rs b/crates/victory-gpu/src/profile.rs deleted file mode 100644 index f5b4b08..0000000 --- a/crates/victory-gpu/src/profile.rs +++ /dev/null @@ -1,329 +0,0 @@ -//! Diagnostics: a sampling profiler of the whole process (title threads, -//! our workers, the driver), switched on by `VICTORY_PROFILE=` (the -//! sampling period of busy threads, 4 by default; idle threads are looked at -//! every 25 periods). Every 5 s it logs, per thread, the CPU time spent and -//! the most frequent call stacks (module!function+offset, innermost first), -//! so a frame's time can be told apart: title code, write watching, -//! translation, driver, or waiting (and where). -//! -//! A sampled thread is suspended for a few microseconds; nothing is -//! allocated or locked while it is. The title's own code shows as -//! `module+rva` (no symbols), ours and the system's by name. - -use std::collections::HashMap; -use std::time::{Duration, Instant}; -use windows_sys::Win32::Foundation::{CloseHandle, FILETIME, HANDLE, INVALID_HANDLE_VALUE}; -use windows_sys::Win32::System::Diagnostics::Debug::{ - CONTEXT, GetThreadContext, RtlLookupFunctionEntry, RtlVirtualUnwind, SYMBOL_INFO, SymFromAddr, - SymInitialize, SymSetOptions, -}; -use windows_sys::Win32::System::Diagnostics::ToolHelp::{ - CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, -}; -use windows_sys::Win32::System::LibraryLoader::GetModuleFileNameW; -use windows_sys::Win32::System::Threading::{ - GetCurrentProcess, GetCurrentProcessId, GetCurrentThreadId, GetThreadDescription, - GetThreadTimes, OpenThread, ResumeThread, SuspendThread, -}; - -const CONTEXT_FULL: u32 = 0x10_0003; -const THREAD_SUSPEND_RESUME: u32 = 0x2; -const THREAD_GET_CONTEXT: u32 = 0x8; -const THREAD_QUERY_INFORMATION: u32 = 0x40; -const DEPTH: usize = 8; -const REPORT: Duration = Duration::from_secs(5); -/// A thread using at least this much CPU per second is "busy". -const BUSY_MS: u64 = 30; - -type Stack = [u64; DEPTH]; - -struct Tracked { - handle: HANDLE, - name: String, - last_cpu_100ns: u64, - cpu_ms_second: u64, - cpu_ms_report: u64, - samples: u64, - stacks: HashMap, -} - -/// Starts the profiler thread when `VICTORY_PROFILE` is set; once. -pub(crate) fn start() { - static ONCE: std::sync::Once = std::sync::Once::new(); - let Some(period) = std::env::var("VICTORY_PROFILE") - .ok() - .map(|v| v.parse::().unwrap_or(4).max(1)) - else { - return; - }; - ONCE.call_once(|| { - let _ = std::thread::Builder::new() - .name("victory-prof".into()) - .spawn(move || run(Duration::from_millis(period))); - }); -} - -fn filetime(t: &FILETIME) -> u64 { - u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime) -} - -fn thread_ids() -> Vec { - let mut ids = Vec::new(); - // SAFETY: a snapshot of our own process's threads, walked and closed. - unsafe { - let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); - if snap == INVALID_HANDLE_VALUE { - return ids; - } - let mut e: THREADENTRY32 = std::mem::zeroed(); - e.dwSize = size_of::() as u32; - let pid = GetCurrentProcessId(); - let mut more = Thread32First(snap, &mut e) != 0; - while more { - if e.th32OwnerProcessID == pid { - ids.push(e.th32ThreadID); - } - more = Thread32Next(snap, &mut e) != 0; - } - CloseHandle(snap); - } - ids -} - -fn thread_name(handle: HANDLE, tid: u32) -> String { - let mut text: *mut u16 = std::ptr::null_mut(); - // SAFETY: an open thread handle and an out pointer; the text is read - // to its NUL (and left allocated: a few bytes per thread). - unsafe { - if GetThreadDescription(handle, &mut text) >= 0 && !text.is_null() { - let mut n = 0; - while *text.add(n) != 0 { - n += 1; - } - let name = String::from_utf16_lossy(std::slice::from_raw_parts(text, n)); - if !name.is_empty() { - return format!("{name}#{tid}"); - } - } - } - format!("thread#{tid}") -} - -fn cpu_100ns(handle: HANDLE) -> u64 { - let mut t: [FILETIME; 4] = [FILETIME { - dwLowDateTime: 0, - dwHighDateTime: 0, - }; 4]; - // SAFETY: an open thread handle and four time structures. - unsafe { - GetThreadTimes(handle, &mut t[0], &mut t[1], &mut t[2], &mut t[3]); - } - filetime(&t[2]) + filetime(&t[3]) -} - -/// The call stack of a thread, innermost first, zero-padded. The thread is -/// suspended meanwhile; nothing here allocates or locks. -fn capture(handle: HANDLE) -> Option { - let mut stack = [0u64; DEPTH]; - // SAFETY: an open thread handle with the rights; the context is ours; - // the unwinding reads the thread's stack, which is stopped. - unsafe { - if SuspendThread(handle) == u32::MAX { - return None; - } - let mut ctx: CONTEXT = std::mem::zeroed(); - ctx.ContextFlags = CONTEXT_FULL; - if GetThreadContext(handle, &mut ctx) != 0 { - for slot in &mut stack { - if ctx.Rip == 0 { - break; - } - *slot = ctx.Rip; - let mut base = 0u64; - let entry = RtlLookupFunctionEntry(ctx.Rip, &mut base, std::ptr::null_mut()); - if entry.is_null() { - // A leaf without unwind data: the return address is on top. - ctx.Rip = *(ctx.Rsp as *const u64); - ctx.Rsp += 8; - } else { - let mut data = std::ptr::null_mut(); - let mut frame = 0u64; - RtlVirtualUnwind( - 0, - base, - ctx.Rip, - entry, - &mut ctx, - &mut data, - &mut frame, - std::ptr::null_mut(), - ); - } - } - } - ResumeThread(handle); - } - (stack[0] != 0).then_some(stack) -} - -/// `module!function+offset`, or `module+rva`. -fn describe(addr: u64, cache: &mut HashMap) -> String { - if let Some(s) = cache.get(&addr) { - return s.clone(); - } - let text = symbolize(addr); - cache.insert(addr, text.clone()); - text -} - -fn symbolize(addr: u64) -> String { - use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; - // SAFETY: plain queries with our buffers. - unsafe { - let mut base = 0u64; - RtlLookupFunctionEntry(addr, &mut base, std::ptr::null_mut()); - let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); - VirtualQuery(addr as *const _, &mut info, size_of_val(&info)); - let region = if base != 0 { - base - } else { - info.AllocationBase as u64 - }; - let mut path = [0u16; 260]; - let n = GetModuleFileNameW(region as *mut _, path.as_mut_ptr(), 260) as usize; - let module = String::from_utf16_lossy(&path[..n]); - let module = module.rsplit('\\').next().unwrap_or("").to_string(); - let module = if module.is_empty() { - format!("{region:#x}") - } else { - module - }; - let mut buf = vec![0u8; size_of::() + 256]; - let sym = buf.as_mut_ptr().cast::(); - (*sym).SizeOfStruct = size_of::() as u32; - (*sym).MaxNameLen = 255; - let mut displacement = 0u64; - if SymFromAddr(GetCurrentProcess(), addr, &mut displacement, sym) != 0 { - let name = std::slice::from_raw_parts( - (*sym).Name.as_ptr().cast::(), - (*sym).NameLen as usize, - ); - let name = String::from_utf8_lossy(name); - let short: String = name.chars().take(90).collect(); - return format!("{module}!{short}+{displacement:#x}"); - } - format!("{module}+{:#x}", addr - region) - } -} - -fn run(period: Duration) { - // SAFETY: symbol handling for our own process, used from this thread only. - unsafe { - SymSetOptions(0x2 | 0x4); // SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS - SymInitialize(GetCurrentProcess(), std::ptr::null(), 1); - } - // SAFETY: no preconditions; returns the caller's thread id. - let me = unsafe { GetCurrentThreadId() }; - let mut threads: HashMap = HashMap::new(); - let mut cache = HashMap::new(); - let (mut refreshed, mut second, mut reported) = ( - Instant::now() - Duration::from_secs(9), - Instant::now(), - Instant::now(), - ); - let mut tick = 0u64; - tracing::info!(period_ms = period.as_millis() as u64, "profiler started"); - loop { - std::thread::sleep(period); - tick += 1; - if refreshed.elapsed() >= Duration::from_secs(1) { - refreshed = Instant::now(); - let ids = thread_ids(); - threads.retain(|tid, t| { - let keep = ids.contains(tid); - if !keep { - // SAFETY: a handle we opened. - unsafe { CloseHandle(t.handle) }; - } - keep - }); - for tid in ids { - if tid == me || threads.contains_key(&tid) { - continue; - } - // SAFETY: opening a thread of our process. - let handle = unsafe { - OpenThread( - THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, - 0, - tid, - ) - }; - if handle.is_null() { - continue; - } - threads.insert( - tid, - Tracked { - handle, - name: thread_name(handle, tid), - last_cpu_100ns: cpu_100ns(handle), - cpu_ms_second: BUSY_MS, - cpu_ms_report: 0, - samples: 0, - stacks: HashMap::new(), - }, - ); - } - } - if second.elapsed() >= Duration::from_secs(1) { - second = Instant::now(); - for t in threads.values_mut() { - let now = cpu_100ns(t.handle); - t.cpu_ms_second = (now - t.last_cpu_100ns.min(now)) / 10_000; - t.cpu_ms_report += t.cpu_ms_second; - t.last_cpu_100ns = now; - } - } - for t in threads.values_mut() { - if t.cpu_ms_second < BUSY_MS && !tick.is_multiple_of(25) { - continue; - } - if let Some(stack) = capture(t.handle) { - t.samples += 1; - *t.stacks.entry(stack).or_insert(0) += 1; - } - } - if reported.elapsed() >= REPORT { - let secs = reported.elapsed().as_secs_f64(); - reported = Instant::now(); - let mut list: Vec<&mut Tracked> = - threads.values_mut().filter(|t| t.samples > 0).collect(); - list.sort_by_key(|t| std::cmp::Reverse((t.cpu_ms_report, t.samples))); - for t in list.into_iter().take(10) { - tracing::info!( - "prof {}: cpu {:.0}% ({} ms), {} samples", - t.name, - t.cpu_ms_report as f64 / 10.0 / secs, - t.cpu_ms_report, - t.samples - ); - let mut stacks: Vec<_> = std::mem::take(&mut t.stacks).into_iter().collect(); - stacks.sort_by_key(|&(_, n)| std::cmp::Reverse(n)); - for (stack, n) in stacks.into_iter().take(4) { - let frames: Vec = stack - .iter() - .take_while(|&&a| a != 0) - .map(|&a| describe(a, &mut cache)) - .collect(); - tracing::info!("prof {:>4}x {}", n, frames.join(" < ")); - } - (t.cpu_ms_report, t.samples) = (0, 0); - } - for t in threads.values_mut() { - (t.cpu_ms_report, t.samples) = (0, 0); - t.stacks.clear(); - } - } - } -} diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index c4b6dd5..a9a4028 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -34,9 +34,403 @@ struct Queue { object: Object, kind: u32, desc: QueueDesc, + /// What the queue was given after a wait for a fence that had not been + /// reached, in order; it runs when the fence gets there. + #[cfg(windows)] + held: std::sync::Mutex>, } const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10); +/// One thing a waiting queue holds back. +#[cfg(windows)] +enum Held { + /// The queue waits for the fence (its address) to reach the value. + Wait(usize, u64), + /// A list of the next submission waits for a memory value. + Value(crate::list::ValueWait), + /// A submission: the lists' host sides, taken from the title's lists + /// (which it may reset meanwhile), and the order they run in. + Run(Vec, Vec), + /// A signal of the queue's, due after what it holds before it. + Signal(usize, u64), +} + +/// The queues that hold something (their addresses). +#[cfg(windows)] +static WAITING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +#[cfg(windows)] +fn lock(mutex: &std::sync::Mutex) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Whether queues wait for fences. `VICTORY_QUEUE_WAIT=0`: they do not, +/// and every submission runs when it is made (as before). +#[cfg(windows)] +fn waits() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE_WAIT").is_none_or(|v| v != "0")) +} + +/// Whether a submission is held list by list: the lists before the first +/// one whose wait for a memory value is not met run at once, and each list +/// that waits is held with the lists after it, behind its own waits. +/// Holding a submission whole made the title's queues wait for each other: +/// a graphics submission was held for a value a compute list writes, and +/// that compute list for a value an earlier list of the same graphics +/// submission writes. Nothing moved until the present forced it, and the +/// title reached its present only after waiting about 2.5 s, every frame +/// (runs 27-30: 2.4-2.9 s from the last submission to the present call, +/// 13-32 ms before waits were honoured; the frame's main graphics +/// submissions, 88 lists, ran forced, the compute lists before them). +/// On by default; `VICTORY_SPLIT_WAITS=0` holds whole submissions, as +/// before. +#[cfg(windows)] +fn split() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SPLIT_WAITS").is_none_or(|v| v != "0")) +} + +/// Whether a list is cut into host lists at its waits for memory values +/// (`crate::list::cut`), and a queue runs a submission part by part: it +/// stands at each wait until the value is in memory, with everything +/// recorded before the wait run and its bottom-of-pipe writes done, as on +/// the console. Held list by list ([`split`]) a wait still held its whole +/// list: the title's lists are chains of jobs, each behind a wait for a +/// value another queue's list writes in the middle of its own chain +/// (frame 858 of run 33: a compute list of 433 commands with 13 waits; +/// graphics lists of the form "341 dispatches, wait, draws"), so two lists +/// each waited for a write behind the other's wait and only the present +/// moved them, in the wrong order. +/// On by default where waits are honoured list by list; +/// `VICTORY_CUT_WAITS=0` holds whole lists, as before. +#[cfg(windows)] +pub(crate) fn cuts() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + waits() && split() && *ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WAITS").is_none_or(|v| v != "0")) +} + +/// Whether a present runs what queues still hold (on by default: a wait +/// is not kept across frames). `VICTORY_WAIT_FORCE=0` keeps it held: for +/// finding out whether the title's waits reach across its presents; a +/// wait nothing ever meets then stops the title for good. +#[cfg(windows)] +fn forces() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WAIT_FORCE").is_none_or(|v| v != "0")) +} + +/// A submission to a queue whose lists are cut at their waits ([`cuts`]). +/// The lists before the first one that waits run at once if the queue +/// holds nothing; the rest goes behind what the queue holds, part by part +/// (`crate::list::detach_parts`): the waits of a part, then its host +/// lists. [`release_held`] runs the queue's line as far as the values are +/// there, now and whenever a submission has run. +#[cfg(windows)] +fn submit_cut(this: This, lists: &[This]) { + let Some(host) = crate::host::host() else { + return; + }; + let first = if lock(&queue(this).held).is_empty() { + lists + .iter() + .position(|&l| crate::list::cut_list(l)) + .unwrap_or(lists.len()) + } else { + 0 + }; + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || { + let named: Vec = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!( + "SUBMIT queue kind {:?} held {} lists {named:?} (the first {first} run at once, the rest part by part)", + Some(queue(this).kind), + first < lists.len() + ) + }); + if first > 0 && crate::host::late() { + // Sent to the card and not waited for: their host sides are taken + // from the title's lists (which it may reset before they have run) + // and come back, with their tables' slots, when they are settled. + let (taken, order) = crate::list::detach(&lists[..first]); + host.execute_late(taken, order); + } else if first > 0 { + let now: Vec<_> = lists[..first] + .iter() + .filter_map(|&l| crate::list::host_list(l)) + .collect(); + host.execute(&now); + // They have run: their descriptor tables' slots are free again, as + // on the path without cuts ([`execute`]). This path replaced that + // one without the call, so the lists that run at once kept their + // slots until the title's reset and the ring ran out as before + // (run 45: 3,143 of 15,942 tables refused in one frame). + crate::list::tables_done(&lists[..first]); + } + if first < lists.len() { + let parts = crate::list::detach_parts(&lists[first..]); + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!( + kind = queue(this).kind, + lists = lists.len(), + run_at_once = first, + parts = parts.len(), + waits = parts.iter().map(|p| p.0.len()).sum::(), + "a submission is given to its queue part by part (its lists wait for memory values)" + ); + } + { + let mut held = lock(&queue(this).held); + for (waits, taken, order) in parts { + held.extend(waits.into_iter().map(Held::Value)); + held.push(Held::Run(taken, order)); + } + } + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + // What ran may be what another queue waits for, and what was just + // given to the queue may be free to run already. + release_held(false); +} + +/// A submission to a queue that honours waits, list by list ([`split`]). +/// shortcut: a wait still holds its whole list, not only the commands +/// after it; and lists named twice among those held stay in one piece. +#[cfg(windows)] +fn submit_split(this: This, lists: &[This]) { + let Some(host) = crate::host::host() else { + return; + }; + let by = crate::list::waits_by_list(lists); + // Behind what the queue already holds, nothing runs now. + let cut = if lock(&queue(this).held).is_empty() { + (0..lists.len()) + .find(|&i| by[i].iter().any(|w| !w.met())) + .unwrap_or(lists.len()) + } else { + 0 + }; + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || { + let named: Vec = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!( + "SUBMIT queue kind {:?} held {} lists {named:?} (the first {cut} run at once)", + Some(queue(this).kind), + cut < lists.len() + ) + }); + if cut > 0 { + let now: Vec<_> = lists[..cut] + .iter() + .filter_map(|&l| crate::list::host_list(l)) + .collect(); + host.execute(&now); + } + if cut < lists.len() { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!( + kind = queue(this).kind, + lists = lists.len(), + run_at_once = cut, + waits = ?by[cut], + "lists of a submission are held for a memory value" + ); + } + let rest = &lists[cut..]; + // A list's host side can be taken once. + let twice = rest.iter().enumerate().any(|(i, l)| rest[..i].contains(l)); + let mut pieces: Vec = Vec::new(); + let mut from = cut; + while from < lists.len() { + // Up to the next list that waits for anything (met or not: it + // is looked at again when its turn comes). + let to = if twice { + lists.len() + } else { + (from + 1..lists.len()) + .find(|&i| !by[i].is_empty()) + .unwrap_or(lists.len()) + }; + let waits: Vec = by[from..to].concat(); + pieces.extend(waits.into_iter().map(Held::Value)); + let (taken, order) = crate::list::detach(&lists[from..to]); + pieces.push(Held::Run(taken, order)); + from = to; + } + lock(&queue(this).held).extend(pieces); + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + // What ran may be what another queue waits for, and what was just held + // may be free to run already. + release_held(false); +} + +/// Adds `what()` to what the queue holds, if it holds anything (it waits +/// for a fence): whether it was added. +#[cfg(windows)] +fn hold(this: This, what: impl FnOnce() -> Held) -> bool { + if this.is_null() { + return false; + } + let mut held = lock(&queue(this).held); + if held.is_empty() { + return false; + } + held.push(what()); + true +} + +/// Runs what waiting queues hold as far as their fences have been reached +/// (`all`: all of it), each queue's in the order it was given. Called +/// where a fence may have moved: after a signal and after a submission (a +/// list's bottom-of-pipe write may be into a fence), never from inside +/// one. +#[cfg(windows)] +pub(crate) fn release_held(all: bool) { + // One caller at a time, so a queue's submissions keep their order. + static RELEASING: std::sync::Mutex<()> = std::sync::Mutex::new(()); + if lock(&WAITING).is_empty() { + return; + } + let _one = lock(&RELEASING); + loop { + let queues = lock(&WAITING).clone(); + let mut moved = false; + for q in queues { + // SAFETY: a live queue: one released is taken off the list. + let held = unsafe { &(*(q as *const Queue)).held }; + let mut held = lock(held); + loop { + match held.first() { + None => break, + Some(&Held::Wait(fence, value)) + if !all && crate::fence::completed(fence as This) < value => + { + break; + } + Some(Held::Value(wait)) if !all && !value_met(wait) => break, + Some(_) => {} + } + match held.remove(0) { + Held::Wait(..) => {} + Held::Value(wait) => { + // Passed at a present without being met: what the + // queue stood at. + if all && !value_met(&wait) { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 16 { + tracing::warn!( + queue = format_args!("{q:#x}"), + ?wait, + "a wait for a memory value was not met at a present: the queue runs on" + ); + } + } + } + Held::Run(lists, order) => { + #[cfg(feature = "diagnostics")] + crate::capture::op(q, || { + format!( + "RUN held submission of {} lists (forced {all})", + order.len() + ) + }); + // Diagnostics: the part behind this one stands at + // waits that are met already, so the two could have + // been one host submission (one wait for the card, + // each range shaders write compared once). + #[cfg(feature = "diagnostics")] + { + let waits = held.iter().take_while(|h| matches!(h, Held::Value(_))).count(); + if waits > 0 + && matches!(held.get(waits), Some(Held::Run(..))) + && held[..waits].iter().all(|h| matches!(h, Held::Value(w) if w.met())) + { + crate::copystat::add(crate::copystat::C::PartsTogether, 1); + } + } + if crate::host::late() + && let Some(host) = crate::host::host() + { + // Not waited for: the host keeps the lists + // until they are settled. + host.execute_late(lists, order); + } else { + let ran = { + let runs: Vec<&crate::host::HostList> = + order.iter().map(|&i| lists[i].host()).collect(); + match crate::host::host() { + Some(host) => { + host.execute(&runs); + true + } + None => false, + } + }; + // They have run: their host lists are used again. + if ran { + crate::list::recycle(lists, &order); + } + } + if all { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Forced, 1); + static ONCE: AtomicBool = AtomicBool::new(false); + if !ONCE.swap(true, Ordering::Relaxed) { + tracing::warn!( + "a queue still held a submission at a present: its fence was not reached" + ); + } + } + } + // Behind what was sent to the card and not waited + // for, if anything was. + Held::Signal(fence, value) => { + if !crate::host::late_signal(fence, value) { + crate::fence::set(fence as This, value); + } + } + } + moved = true; + } + if held.is_empty() { + lock(&WAITING).retain(|&w| w != q); + } + } + if !moved { + break; + } + } +} + +/// Whether a queue may pass `wait`: memory holds the value, or, with +/// submissions sent to the card without a wait (`crate::host::late`), it +/// will once those in the air have run. +#[cfg(windows)] +fn value_met(wait: &crate::list::ValueWait) -> bool { + wait.met() || (crate::host::late() && crate::host::late_met(wait)) +} + fn queue<'a>(this: This) -> &'a Queue { // SAFETY: called from queue methods only. unsafe { &*this.cast::() } @@ -61,6 +455,8 @@ pub(crate) extern "system" fn create( }, kind: desc.kind, desc, + #[cfg(windows)] + held: Default::default(), }); object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out) } @@ -107,11 +503,17 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT ) } extern "system" fn release(this: This) -> u32 { - object::release_boxed::(this) + let left = object::release_boxed::(this); + #[cfg(windows)] + if left == 0 { + lock(&WAITING).retain(|&q| q != this as usize); + } + left } -/// Runs the lists' host lists and waits for them (decision 0007). -extern "system" fn execute(_: This, count: u32, lists: *const This) { +/// Runs the lists' host lists and waits for them (decision 0007). A queue +/// that waits for a fence keeps them until the fence is reached. +extern "system" fn execute(this: This, count: u32, lists: *const This) { if lists.is_null() { return; } @@ -119,13 +521,64 @@ extern "system" fn execute(_: This, count: u32, lists: *const This) { if let Some(host) = crate::host::host() { // SAFETY: the title passes `count` lists. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) }; + if cuts() && !this.is_null() { + submit_cut(this, lists); + return; + } + if waits() && split() && !this.is_null() { + submit_split(this, lists); + return; + } + // A list that waits for a memory value not there yet: the queue + // holds the submission, as it does behind a fence. + if waits() && !this.is_null() { + let unmet = crate::list::unmet_waits(lists); + if !unmet.is_empty() { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!(kind = queue(this).kind, ?unmet, "a submission is held for a memory value"); + } + lock(&queue(this).held).extend(unmet.into_iter().map(Held::Value)); + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + } + let kept = hold(this, || { + let (taken, order) = crate::list::detach(lists); + Held::Run(taken, order) + }); + // Diagnostics: the order submissions are made in, next to the + // commands of the frame's `ops` file (which are in recording order). + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || { + let kind = (!this.is_null()).then(|| queue(this).kind); + // The lists as the frame's other lines name them (their host sides). + let named: Vec = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!("SUBMIT queue kind {kind:?} held {kept} lists {named:?}") + }); + if kept { + return; + } let host_lists: Vec<_> = lists .iter() .filter_map(|&l| crate::list::host_list(l)) .collect(); - host.execute_title(&host_lists); + host.execute(&host_lists); + crate::list::tables_done(lists); + // What the lists wrote at the bottom of the pipe may be a fence + // another queue waits for. + release_held(false); return; } + let _ = this; static ONCE: AtomicBool = AtomicBool::new(false); if !ONCE.swap(true, Ordering::Relaxed) { tracing::warn!(count, "command lists submitted; no host GPU runs them"); @@ -157,15 +610,80 @@ 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 { +extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } + // A queue that waits signals after what it holds. + #[cfg(windows)] + if hold(this, || Held::Signal(fence as usize, value)) { + return S_OK; + } + // Behind the submissions sent to the card and not waited for: the + // fence is set when they are settled. + #[cfg(windows)] + if crate::host::late_signal(fence as usize, value) { + return S_OK; + } + let _ = this; crate::fence::signal(fence, value) } -/// 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 } +/// From here on the queue runs nothing it is given until `fence` reaches +/// `value`: how the console orders work between queues (the title's +/// compute queue waits for the depth the graphics queue draws). Our +/// submissions run when they are made, so a wait for a value already +/// reached is nothing; otherwise what the queue is given next is held +/// (`Held`) until a signal or a list's bottom-of-pipe write gets the +/// fence there. +extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { + if fence.is_null() { + return E_INVALIDARG; + } + #[cfg(windows)] + if !this.is_null() { + let now = crate::fence::completed(fence); + // Whether the title uses this at all (the first calls). + { + static CALLS: AtomicU64 = AtomicU64::new(0); + if CALLS.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!(kind = queue(this).kind, now, value, "a queue is told to wait for a fence"); + } + } + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || format!("WAIT queue kind {} for fence {fence:?} value {value} (now {now})", queue(this).kind)); + let behind = { + let mut held = lock(&queue(this).held); + let behind = !held.is_empty() || now < value; + if behind && waits() { + held.push(Held::Wait(fence as usize, value)); + } + behind + }; + if behind { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!( + kind = queue(this).kind, + now, + value, + held = waits(), + "a queue waits for a fence not reached yet" + ); + } + } + if behind && waits() { + { + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + // The fence may have got there meanwhile. + release_held(false); + } + } + 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,6 +745,7 @@ 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) } @@ -241,6 +760,24 @@ extern "system" fn present( plane_parameters: *const Plane, _parameters: *const u8, ) -> HRESULT { + #[cfg(all(windows, feature = "diagnostics"))] + crate::copystat::present_begins(); + // Submissions sent to the card and not waited for are settled first, + // and what that frees runs in its own order, before anything is forced. + #[cfg(windows)] + if crate::host::late() && !crate::host::late_free_present() { + crate::host::settle_for_present(); + release_held(false); + crate::host::settle_for_present(); + } else if crate::host::late() { + // The present is sent ahead too: what waits for a value a flight + // will write runs behind that flight, and nothing is settled here. + release_held(false); + } + // shortcut: what a queue still holds at a present runs now, whatever + // its fence: a wait is not kept across frames. + #[cfg(windows)] + release_held(forces()); let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; if frame.is_power_of_two() { let (draws, dispatches) = crate::list::take_counts(); @@ -271,8 +808,11 @@ extern "system" fn present( } } #[cfg(all(windows, feature = "diagnostics"))] - if crate::capture::listed(frame) { - crate::capture::dump_targets(frame); + { + crate::capture::frame_drew(frame, crate::draw::drawn()); + if crate::capture::listed(frame) { + crate::capture::dump_targets(frame); + } } #[cfg(windows)] if planes > 0 @@ -356,7 +896,7 @@ const PAGE: u64 = 64 << 10; /// `CopyPageMappingsBatchX(count, batches, pool, pool pages, flags)`: maps /// pages of a pool (memory the title mapped physical pages into) at the -/// batches' addresses. Grand Theft Auto VI streams textures into pool pages +/// batches' addresses. The title 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. @@ -402,9 +942,7 @@ extern "system" fn copy_page_mappings( } if !ok { static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed") - }); + ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed")); } S_OK } @@ -440,7 +978,7 @@ const METHODS: [(usize, *const ()); 15] = [ /// Newer titles' queues have two more methods before Signal, which moved /// from 0x70 to 0x80: every slot from 0x70 on is two later (taken here as /// starting exactly at 0x70, the methods before it kept in place). -/// Inferred from Grand Theft Auto VI's calls: Signal 0x80 `(fence, +/// Inferred from the title's calls: Signal 0x80 `(fence, /// value)`, timestamp frequency 0x90 (title+0x24841a6), suspend and resume /// 0xb8/0xc0, PresentX 0x100, the frame-token submission 0x118 `(count, /// lists, token, flags)` (title+0x24821dd). @@ -508,7 +1046,7 @@ mod tests { assert_eq!(slot:: u32>(q, 0x10)(q), 0); } - /// Grand Theft Auto VI's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`. + /// The title's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`. #[test] fn console_queues_are_created_as_on_pc() { let null = std::ptr::null(); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 65f5ee6..f38c7cd 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -178,8 +178,8 @@ fn footprint(desc: &ResourceDesc) -> Option { && let Some(t) = texture_layout(desc) { // As the console: the layout's own alignment unless more is asked - // (4 KiB for 4 KiB modes, where PC says 64 KiB). Grand Theft Auto - // VI keeps these sizes in its texture tables, and its streaming + // (4 KiB for 4 KiB modes, where PC says 64 KiB). + // The title keeps these sizes in its texture tables, and its streaming // asserts when they disagree with the streamed layout. let alignment = desc.alignment.max(t.alignment); if !alignment.is_power_of_two() { @@ -228,7 +228,6 @@ 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. -#[cfg(windows)] pub(crate) fn pc_format(format: u32) -> u32 { match format { 118 => 45, @@ -238,8 +237,340 @@ pub(crate) fn pc_format(format: u32) -> u32 { } } -/// The typeless format of a format's family (itself if it has none). +/// The format of a texture the host GPU renders to or writes as unordered +/// access, for the title's `format`. The console's GPU does both with the +/// 16-bit colour formats B5G5R5A1 (86) and B4G4R4A4 (115), and +/// the title has full-screen targets in both; a host that refuses either use +/// (NVIDIA) refused the whole texture, so every pass that wrote it drew +/// nothing. There 8-bit RGBA stands in: the same channels in the same +/// order, every 4-bit level exact and every 5-bit level within 1/510. +/// The title's pipelines and views of such targets name the stand-in too +/// ([`view_format`], the host view checks). +/// shortcut: copies between such a target and a texture the title fills +/// itself in the 16-bit format are skipped (`stands_in`); convert them +/// if a pass turns out to need one. +pub(crate) fn target_format(format: u32) -> u32 { + const STAND_INS: [(u32, u32); 2] = [(86, 28), (115, 28)]; + let Some(i) = STAND_INS.iter().position(|&(f, _)| f == format) else { + return format; + }; + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::*; + static REFUSED: std::sync::OnceLock<[bool; 2]> = std::sync::OnceLock::new(); + let refused = REFUSED.get_or_init(|| { + STAND_INS.map(|(f, _)| { + let Some(host) = crate::host::host() else { + return false; + }; + let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(f as i32), + ..Default::default() + }; + // SAFETY: a plain query into our own structure. + let asked = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_FORMAT_SUPPORT, + (&raw mut support).cast(), + size_of_val(&support) as u32, + ) + }; + let both = D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0 + | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0; + let refused = asked.is_err() || support.Support1.0 & both != both; + if refused { + tracing::info!(format = f, "the host does not render to this format: 8-bit RGBA stands in"); + } + refused + }) + }); + if refused[i] { + return STAND_INS[i].1; + } + } + format +} + +/// Whether the host copy of the title texture `this` is in a stand-in +/// format ([`target_format`]): its texels are not laid out as the title's. +#[cfg(windows)] +pub(crate) fn stands_in(this: This) -> bool { + if this.is_null() { + return false; + } + let own = pc_format(resource(this).desc.format); + target_format(own) != own + && host_resource(this) + // SAFETY: a live resource. + .is_some_and(|host| unsafe { host.GetDesc() }.Format.0 as u32 == target_format(own)) +} + +/// Depth textures the title also asks unordered access for (the console +/// allows both; the host copy loses the unordered access): how many were +/// made, and how often such a texture was bound as the depth target, +/// cleared as depth, and asked for an unordered access view the host could +/// not give. Measured to decide what such textures need (a colour twin, or +/// to be colour textures altogether). +pub(crate) static DEPTH_UNORDERED: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Whether the title asked for both depth and unordered access for `this`. +#[cfg(windows)] +pub(crate) fn depth_and_unordered(this: This) -> bool { + !this.is_null() && resource(this).desc.flags & 6 == 6 +} + +/// The colour twin of a depth texture the title also writes as unordered +/// access. The console allows both on one texture; the host gives a depth +/// texture no unordered access, so shaders write a colour texture of the +/// same size and format family instead, and one is copied into the other +/// when a side is used after the other was written +/// (`HostList::twin_use`). +/// shortcut: whole textures are copied, not the mips and slices written. +/// A depth texture with a stencil plane gets a twin for each plane ( +/// the title's tiled lighting writes each pixel's material class into +/// the depth plane and masks into the stencil plane, then draws each class +/// with the depth test "equal"): the stencil plane's is copied through a +/// buffer, the depth plane's is drawn into the plane by a pass of ours +/// (`HostList::pass_plane`). Unordered access views of a multisampled +/// texture stay null. +#[cfg(windows)] +pub(crate) struct Twin { + /// The colour texture and the state it is in, as a host copy's. + pub(crate) colour: std::sync::Arc, + /// Which side lacks what the other was written last, after the lists + /// submitted so far: bit 0 the depth texture, bit 1 the twin. + pub(crate) behind: std::sync::atomic::AtomicU32, + /// For a depth texture with a stencil plane, `colour` is the twin of + /// that plane (8 bits a texel) and this the buffer the two are copied + /// through: no colour format shares a family with a depth-stencil + /// format, but the host copies between a buffer and one plane. + pub(crate) through: Option, + /// For a depth texture with a stencil plane: the twin of its depth + /// plane, 16 bits a texel for the console's 16-bit depth-stencil + /// formats and a 32-bit float otherwise. No host colour format holds + /// the bits of a 24-bit depth plane, so the two are not copied: a pass + /// draws the twin into the plane. + pub(crate) plane: Option>, +} + +#[cfg(windows)] +impl Drop for Twin { + fn drop(&mut self) { + TWINS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Colour twins alive, depth textures with unordered access left without +/// one, and the copies recorded into depth textures and into twins since +/// the last frame-rate line. +#[cfg(windows)] +pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Depth planes drawn from their twins by the pass since the last +/// frame-rate line; and since the start, how often a depth plane's twin +/// lacked what was written to the plane (not given to it), and how often a +/// depth plane was used in the list that had written its twin, before the +/// pass (which runs when the list closes). +#[cfg(windows)] +pub(crate) static PLANES: [std::sync::atomic::AtomicU64; 3] = + [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// The colour twin of title texture `this`, if it has one. +#[cfg(windows)] +pub(crate) fn twin(this: This) -> Option> { + if this.is_null() { + return None; + } + hosted(this, true).and_then(|made| made.1) +} + +/// The twin's texture, for the unordered access views of `this`. +#[cfg(windows)] +pub(crate) fn twin_resource<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (_, twin) = hosted(this, true)?; + // SAFETY: as in `host_resource`: the twin lives as long as the host + // copy, which a depth texture keeps until the title releases it. + twin.map(|t| unsafe { &*std::ptr::from_ref(&t.colour.texture) }) +} + +/// The texture of the twin of the depth plane of `this`, a depth texture +/// with a stencil plane, for the unordered access views of that plane. +#[cfg(windows)] +pub(crate) fn twin_plane_resource<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (_, twin) = hosted(this, true)?; + let twin = twin?; + // SAFETY: as in `twin_resource`. + twin.plane + .as_ref() + .map(|p| unsafe { &*std::ptr::from_ref(&p.texture) }) +} + +/// The colour twin for a texture described by `desc` whose host copy is +/// `depth`, if the title asks for depth and unordered access both and the +/// host can copy between the two: the same size, mips and slices in the +/// depth format's typeless family (R16 for 16-bit depth, R32 for 32-bit), +/// or R8 for the stencil plane of a format that has one, with unordered +/// access only. A format with a stencil plane gets a twin for its depth +/// plane too, R16 for the console's 16-bit depth-stencil formats and R32 +/// otherwise. `VICTORY_DEPTH_TWINS=0` makes none (such views stay null), +/// `VICTORY_DEPTH_TWINS=stencil` only those of formats with a stencil +/// plane, `VICTORY_DEPTH_TWINS=nodepth` none for the depth planes of such +/// formats. #[cfg(windows)] +fn twin_texture( + desc: &ResourceDesc, + depth: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, +) -> Option> { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + const DEPTH_AND_UNORDERED: u32 = 6; + const UNORDERED: u32 = 4; + const UNORDERED_ACCESS: u32 = 0x8; + // R32 and R16 typeless: the families of the depth formats of one plane. + const ONE_PLANE: [u32; 2] = [39, 53]; + if desc.dimension == BUFFER || desc.flags & DEPTH_AND_UNORDERED != DEPTH_AND_UNORDERED { + return None; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_none_or(|v| v != "0")) { + return None; + } + // R32G8X24 and R24G8 typeless: depth with a stencil plane, whose twin + // is R8 typeless. + const WITH_STENCIL: [u32; 2] = [19, 44]; + const R8_TYPELESS: u32 = 60; + let typeless = family(pc_format(desc.format)); + let stencil = WITH_STENCIL.contains(&typeless); + static STENCIL_ONLY: std::sync::OnceLock = std::sync::OnceLock::new(); + let stencil_only = *STENCIL_ONLY + .get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_some_and(|v| v == "stencil")); + if !stencil && stencil_only { + return None; + } + if !(stencil || ONE_PLANE.contains(&typeless)) || desc.sample_count > 1 { + TWINS[1].fetch_add(1, Relaxed); + return None; + } + let host = crate::host::host()?; + let mut d = *desc; + d.layout = 0; + d.alignment = 0; + d.flags = UNORDERED; + d.format = if stencil { R8_TYPELESS } else { typeless }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let mut texture: Option = None; + // SAFETY: the description has the host layout, as in `host_texture`; + // the out pointer is ours. + let made = unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32), + None, + &mut texture, + ) + }; + if let Err(e) = made { + tracing::warn!(error = %e, desc = ?d, "no colour twin for a depth texture"); + } + let Some(texture) = texture else { + TWINS[1].fetch_add(1, Relaxed); + return None; + }; + crate::host::name(&texture, || { + format!("depth twin {}x{} f{}", d.width, d.height, d.format) + }); + // The buffer a stencil plane and its twin are copied through: as big + // as the plane's mips and slices laid out for a copy (they follow the + // depth plane's in the texture's subresources). + let through = if stencil { + // SAFETY: a live texture. + let of = unsafe { depth.GetDesc() }; + let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize); + let mut bytes = 0; + // SAFETY: a plain query; the out pointer is ours. + unsafe { + host.device.GetCopyableFootprints( + &of, + planes, + planes, + 0, + None, + None, + None, + Some(&mut bytes), + ); + } + let Some(buffer) = host.uav_buffer(bytes) else { + TWINS[1].fetch_add(1, Relaxed); + return None; + }; + Some(buffer) + } else { + None + }; + // The twin of the depth plane of a format with a stencil plane: R16 + // typeless (53) for the console's 16-bit depth-stencil formats (118 to + // 120), whose shaders write 16-bit steps, R32 typeless (39) otherwise. + static NO_PLANE: std::sync::OnceLock = std::sync::OnceLock::new(); + let no_plane = *NO_PLANE + .get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_some_and(|v| v == "nodepth")); + let plane = if stencil && !no_plane { + d.format = if (118..=120).contains(&desc.format) { + 53 + } else { + 39 + }; + let mut texture: Option = None; + // SAFETY: as for the first twin. + let made = unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32), + None, + &mut texture, + ) + }; + if let Err(e) = made { + tracing::warn!(error = %e, desc = ?d, "no twin for a depth plane"); + } + texture.map(|texture| { + crate::host::name(&texture, || { + format!("depth plane twin {}x{} f{}", d.width, d.height, d.format) + }); + std::sync::Arc::new(HostTexture::new(texture, UNORDERED_ACCESS)) + }) + } else { + None + }; + TWINS[0].fetch_add(1, Relaxed); + Some(std::sync::Arc::new(Twin { + colour: std::sync::Arc::new(HostTexture::new(texture, UNORDERED_ACCESS)), + behind: std::sync::atomic::AtomicU32::new(0), + through, + plane, + })) +} + +/// The typeless format of a format's family (itself if it has none). pub(crate) fn family(format: u32) -> u32 { const FAMILIES: [(u32, u32); 22] = [ (1, 4), @@ -276,25 +607,24 @@ pub(crate) fn family(format: u32) -> u32 { } /// sRGB formats and their linear twins. -#[cfg(windows)] pub(crate) const SRGB: [(u32, u32); 3] = [(29, 28), (91, 87), (93, 88)]; /// The format a view of a title texture must name when its host copy is /// typeless (see [`DEPTH_FORMATS`], [`SRGB`]): the title's own; `None` if /// the host copy is typed. -#[cfg(windows)] pub(crate) fn view_format(this: This) -> Option { - let own = pc_format(resource(this).desc.format); + // First: a view of no resource (a typed null view) has none. let host = host_resource(this)?; + let own = pc_format(resource(this).desc.format); // SAFETY: a live resource. let format = unsafe { host.GetDesc() }.Format.0 as u32; - (format != own).then_some(own) + // A stand-in target is typed. + (format != own && format != target_format(own)).then_some(own) } /// Depth formats with their typeless family: depth textures that shaders /// read are made typeless on the host, which only allows views of /// typeless depth resources. -#[cfg(windows)] pub(crate) const DEPTH_FORMATS: [(u32, u32); 4] = [(20, 19), (40, 39), (45, 44), (55, 53)]; /// Mip levels, the full chain for 0. @@ -330,13 +660,29 @@ pub(crate) struct PlacedFootprint { impl PlacedFootprint { /// The bytes it spans in a buffer: every row pitched but the last. - #[cfg(windows)] pub(crate) fn bytes(&self) -> Option { let (element, block) = element(self.format)?; let lines = u64::from(self.height).div_ceil(block) * u64::from(self.depth); let last = u64::from(self.width).div_ceil(block) * element; Some(u64::from(self.row_pitch) * lines.saturating_sub(1) + last) } + + /// For a read back through a host buffer: this footprint at offset 0 + /// with its rows pitched as the host wants them (multiples of 256 + /// bytes), then the bytes that buffer needs, the bytes of a row, the + /// rows, and the title's own pitch. + pub(crate) fn host_rows(&self) -> Option<(PlacedFootprint, [u64; 4])> { + let (element, block) = element(self.format)?; + let lines = (u64::from(self.height).div_ceil(block) * u64::from(self.depth)).max(1); + let row = u64::from(self.width).div_ceil(block) * element; + let pitch = row.max(1).next_multiple_of(256); + let host = PlacedFootprint { + offset: 0, + row_pitch: u32::try_from(pitch).ok()?, + ..*self + }; + Some((host, [pitch * lines, row, lines, u64::from(self.row_pitch)])) + } } const _: () = assert!(size_of::() == 32); @@ -575,7 +921,7 @@ static ALLOCATOR: std::sync::OnceLock<(AllocRoutine, FreeRoutine)> = std::sync:: /// Committed resources get their memory from the title's general /// allocator, as on the console, where titles hook it to place graphics -/// memory themselves (Grand Theft Auto VI places its back buffers in a +/// memory themselves (the title places its back buffers in a /// block of its own and checks they fill it). The runtime names it before /// the device exists. pub fn use_allocator(alloc: AllocRoutine, free: FreeRoutine) { @@ -651,6 +997,12 @@ impl Memory { .ok_or(E_INVALIDARG)?; // SAFETY: the size is non-zero. let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(E_OUTOFMEMORY)?; + // The big ones are named in the log: the memory line counts our own + // allocations by size, and these are the title's memory given out + // of ours (a heap it made through the device, a descriptor heap). + if info.size >= 32 << 20 { + tracing::info!(mb = info.size >> 20, at = ?ptr, "memory for the title from our allocator (a heap or a descriptor heap)"); + } Ok(Memory { ptr, layout, @@ -752,9 +1104,10 @@ struct Resource { heap_flags: u32, backing: Backing, /// Textures also live on the host GPU (decision 0007); buffers do not - /// yet. + /// yet. With, for a depth texture the title also writes as unordered + /// access, the colour texture shaders write instead ([`Twin`]). #[cfg(windows)] - host: Option>, + host: Hosted, } /// A title texture's host copy and the state it is in. The title's barriers @@ -767,174 +1120,680 @@ struct Resource { pub(crate) struct HostTexture { pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, pub(crate) state: std::sync::atomic::AtomicU32, - /// Mip levels in the title texture. - pub(crate) title_mips: u32, - /// Top title mips omitted from the host copy. - mip_drop: u32, - is_3d: bool, + /// The bytes the host gives it. + bytes: u64, + /// Whether its contents come from title memory ([`fills`]): counted in + /// [`KINDS`] while it lives. + filled: bool, } +/// What a title texture has on the host: its host copy and, for a depth +/// texture shaders also write, the colour twin. #[cfg(windows)] -impl HostTexture { - pub(crate) fn mip_drop(&self) -> u32 { - self.mip_drop - } +type Made = (std::sync::Arc, Option>); + +/// A title texture's host side. The host copy is made when something first +/// uses the texture, not when the title creates it: the title +/// had created 3,871 textures (9.2 GB on the host) before its world's first +/// frame, of which a frame's lists name some hundreds (run 23), on a card +/// with 12 GB. A title texture is memory the title has either way; its host +/// copy is the card's. +#[cfg(windows)] +struct Hosted { + /// The host copy (and twin) once made. Taken out again only by + /// [`let_go_idle`] and when the title releases the resource. + made: std::sync::Mutex>, + /// The state and clear value the title created the texture with. + state: u32, + clear: Option<[u32; 5]>, + /// When the host copy was last asked for (`crate::host::moment`), + /// written under `made`'s lock. + used: std::sync::atomic::AtomicU64, + /// The host refused to make it: not tried again. + refused: std::sync::atomic::AtomicBool, + /// Its host copy was let go as idle once. + gone: std::sync::atomic::AtomicBool, + /// A texture of [`PLACED_TEXTURES`]. + placed: std::sync::atomic::AtomicBool, +} + +/// Counts for the memory line: host copies of textures the title fills +/// alive and their bytes; such copies let go as idle since the start and +/// their bytes; made again after that and their bytes; and host copies made +/// since the start. +#[cfg(windows)] +pub(crate) static KINDS: [std::sync::atomic::AtomicU64; 7] = + [const { std::sync::atomic::AtomicU64::new(0) }; 7]; - pub(crate) fn host_mips(&self) -> u32 { - self.title_mips.saturating_sub(self.mip_drop).max(1) - } +/// Every title texture alive (not buffers), by address: for the sweep and +/// the memory line. A texture leaves the table before it is freed. +#[cfg(windows)] +static TEXTURES: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); - /// The host subresource of a console subresource, or `None` when it - /// names one of the dropped top mips. - pub(crate) fn host_subresource(&self, console_sub: u32) -> Option { - remap_subresource(console_sub, self.title_mips, self.mip_drop, self.is_3d) - } +#[cfg(windows)] +fn textures() -> std::sync::MutexGuard<'static, std::collections::BTreeSet> { + TEXTURES.lock().unwrap_or_else(|e| e.into_inner()) } -/// A console subresource index as the index of the host texture whose top -/// `mip_drop` mips were omitted; `None` for a dropped mip. +/// The title textures the host renders to or writes (targets, depth, +/// unordered access), by the address of their memory: what a view the +/// title places in that memory in another format shows ([`alias_of`]). A +/// texture leaves the table before it is freed. #[cfg(windows)] -pub(crate) fn remap_subresource( - console_sub: u32, - title_mips: u32, - mip_drop: u32, - is_3d: bool, -) -> Option { - if mip_drop == 0 { - return Some(console_sub); - } - let title_mips = title_mips.max(1); - let host_mips = title_mips.saturating_sub(mip_drop).max(1); - if is_3d { - if !(mip_drop..title_mips).contains(&console_sub) { - return None; - } - return Some(console_sub - mip_drop); +static TARGETS_AT: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// For `this`, a texture made for a view the title placed in memory +/// ([`texture_at`]): the title texture the host writes that lies in the +/// same memory, if there is one of the same size, levels and layers with +/// texels of the same width. The console reads such a texture through the +/// view as it is +/// (the title packs light as R9G9B9E5 into R32_UINT textures +/// with compute shaders, which cannot write R9G9B9E5, and samples them +/// through R9G9B9E5 views placed at the textures' addresses: the sky, the +/// sky and light probes, the bounced light the lighting pass adds). On the +/// host the two are two textures and what the shaders wrote exists in one +/// of them only: the other was filled from title memory, which nothing +/// writes, so everything read through such a view was black. +/// Textures of several levels or layers count too (the screen probes' +/// light atlas has four levels, the camera's sky light cache six layers, +/// the cloud and sky tables are volumes): only textures of one level and +/// one layer were found at first, and the programs behind the others read +/// the title's unwritten memory - the sky light cache's second stage wrote +/// all zeros from a first stage that held light (run 88). +/// `VICTORY_ALIAS_COPY=0`: none is found, as before; `=1`: only textures +/// of one level and one layer, as at first. +#[cfg(windows)] +pub(crate) fn alias_of(this: This) -> Option { + use std::sync::atomic::Ordering::Relaxed; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if this.is_null() + || !*ON.get_or_init(|| std::env::var_os("VICTORY_ALIAS_COPY").is_none_or(|v| v != "0")) + { + return None; } - let mip = console_sub % title_mips; - let slice = console_sub / title_mips; - if mip < mip_drop { + static WHOLE: std::sync::OnceLock = std::sync::OnceLock::new(); + let whole = + *WHOLE.get_or_init(|| std::env::var_os("VICTORY_ALIAS_COPY").is_none_or(|v| v != "1")); + let r = resource(this); + // A level count of 0 asks for a full chain: not counted here. + let one = |d: &ResourceDesc| { + d.dimension != BUFFER + && d.mip_levels >= 1 + && d.depth_or_array_size >= 1 + && (whole || (d.mip_levels == 1 && d.depth_or_array_size == 1)) + && d.sample_count <= 1 + }; + if !r.host.placed.load(Relaxed) || !fills(&r.desc) || !one(&r.desc) { return None; } - Some(slice * host_mips + mip - mip_drop) + // Under the table's lock: a texture leaves it before it is freed. + let targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner()); + let other = *targets.get(&(r.data() as u64))? as This; + let o = resource(other); + const DEPTH: u32 = 0x2; + let same = one(&o.desc) + && o.desc.dimension == r.desc.dimension + && o.desc.width == r.desc.width + && o.desc.height == r.desc.height + && o.desc.mip_levels == r.desc.mip_levels + && o.desc.depth_or_array_size == r.desc.depth_or_array_size + && o.desc.flags & DEPTH == 0 + && target_format(o.desc.format) == o.desc.format + && element(o.desc.format).is_some_and(|e| e.1 == 1 && Some(e) == element(r.desc.format)); + same.then_some(other) +} + +/// Whether host copies are made on first use. On by default; +/// `VICTORY_LAZY_TEXTURES=0` makes each when the title creates its texture, +/// as before. +#[cfg(windows)] +fn lazy() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_TEXTURES").is_none_or(|v| v != "0")) } -/// A texture's host mip-drop count and surviving host mip count. +/// Whether a texture described by `desc` takes its contents from title +/// memory: one the host neither renders to nor writes (no target, depth or +/// unordered access flag). Its host copy can be made again from that +/// memory; any other texture's contents exist on the host alone. #[cfg(windows)] -pub(crate) fn host_mip_info(this: This) -> (u32, u32) { - host_copy(this).map_or((0, 0), |h| (h.mip_drop, h.host_mips())) +fn fills(desc: &ResourceDesc) -> bool { + const TARGET_DEPTH_UNORDERED: u32 = 0x7; + desc.dimension != BUFFER && desc.flags & TARGET_DEPTH_UNORDERED == 0 } -/// Most top mips a sampled texture may lose. -const MAX_MIP_DROP: u32 = 3; +/// Whether the title fills texture `this` itself ([`fills`]). +#[cfg(windows)] +pub(crate) fn title_fills(this: This) -> bool { + !this.is_null() && fills(&resource(this).desc) +} -/// Automatic mip-drop pressure raised when a host texture allocation runs -/// out of memory. +/// Whether `this` is a texture whose host copy is not made yet (and may +/// still be): a descriptor slot written with a view of it waits +/// (`crate::descriptor::make_waiting`). #[cfg(windows)] -static OOM_MIP_PRESSURE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); +pub(crate) fn host_waits(this: This) -> bool { + if this.is_null() || !lazy() { + return false; + } + let r = resource(this); + r.desc.dimension != BUFFER + && !r.host.refused.load(std::sync::atomic::Ordering::Relaxed) + && r.host.made.lock().unwrap_or_else(|e| e.into_inner()).is_none() +} -/// `VICTORY_TEXTURE_MIP_DROP`, if set (`0..=3`; invalid values count as unset). +/// The host side of title texture `this`: made now if it is not there and +/// `make` says so. `None` for buffers and for textures the host refuses. #[cfg(windows)] -fn configured_mip_drop() -> Option { - static CONFIGURED: std::sync::OnceLock> = std::sync::OnceLock::new(); - *CONFIGURED.get_or_init(|| { - std::env::var("VICTORY_TEXTURE_MIP_DROP") - .ok() - .and_then(|v| v.trim().parse::().ok()) - .map(|n| n.min(MAX_MIP_DROP)) - }) +fn hosted(this: This, make: bool) -> Option { + use std::sync::atomic::Ordering::Relaxed; + let r = resource(this); + if r.desc.dimension == BUFFER { + return None; + } + let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + if made.is_none() { + if !make || r.host.refused.load(Relaxed) { + return None; + } + let clear = r + .host + .clear + .as_ref() + .map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast::()); + let Some(texture) = host_texture(&r.desc, r.host.state, clear) else { + r.host.refused.store(true, Relaxed); + return None; + }; + let twin = twin_texture(&r.desc, &texture); + // One line per depth texture with unordered access: its address is + // the one target dumps and the captured frame's list of commands + // name. + if r.desc.flags & 6 == 6 { + tracing::info!( + resource = ?this, + desc = ?r.desc, + twin = twin.is_some(), + "depth texture with unordered access" + ); + } + let state = crate::host::legal_state(&texture, crate::host::texture_state(r.host.state)); + let mut host = HostTexture::new(texture, state); + host.filled = fills(&r.desc); + if host.filled { + KINDS[0].fetch_add(1, Relaxed); + KINDS[1].fetch_add(host.bytes, Relaxed); + } + if r.host.gone.load(Relaxed) { + KINDS[4].fetch_add(1, Relaxed); + KINDS[5].fetch_add(host.bytes, Relaxed); + } + KINDS[6].fetch_add(1, Relaxed); + *made = Some((std::sync::Arc::new(host), twin)); + // Slots the title wrote with views of it while it had no host copy + // are made before the next submission runs. + crate::descriptor::texture_made(this as usize); + } + r.host.used.store(crate::host::moment(), Relaxed); + made.clone() +} + +/// The host copy of title texture `this` if it is made, without making it +/// (for diagnostics, which must not count as a use). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn host_made<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (host, _) = hosted(this, false)?; + // SAFETY: as in `host_resource`. + Some(unsafe { &*std::ptr::from_ref(&host.texture) }) } -/// Baseline mip drop: the user's setting, otherwise one level on adapters -/// with at most 8.5 GiB of dedicated memory (RX 580-class budgets). +/// Whether more host copies of textures the title fills may be made for +/// shaders that pick textures by index (`draw.rs` `heap_textures`): always +/// up to `FLOOR` bytes of them, beyond that while the card's memory in use +/// by this process is under nine tenths of the budget the system gives it +/// ([`room_percent`] says another share; `VICTORY_TEXTURE_BUDGET_MB` sets a +/// limit on those copies' bytes instead). Past the budget the system moves +/// the card's memory into the PC's, which ended runs 20 and 24. #[cfg(windows)] -fn requested_mip_drop() -> u32 { - let automatic = match crate::host::device_memory() { - Some(memory) if memory > 0 && memory <= (17 << 29) => 1, - _ => 0, - }; - configured_mip_drop() - .unwrap_or(automatic) - .max(OOM_MIP_PRESSURE.load(std::sync::atomic::Ordering::Relaxed)) - .min(MAX_MIP_DROP) +pub(crate) fn room() -> bool { + use std::sync::atomic::Ordering::Relaxed; + const FLOOR: u64 = 2 << 30; + const WITHOUT_BUDGET: u64 = 4 << 30; + static LIMIT: std::sync::OnceLock> = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + let mb = std::env::var("VICTORY_TEXTURE_BUDGET_MB").ok()?; + mb.trim().parse::().ok().map(|mb| mb << 20) + }); + let filled = KINDS[1].load(Relaxed); + if let Some(limit) = limit { + return filled < limit; + } + if filled < FLOOR { + return true; + } + match crate::host::host().and_then(|h| h.video_memory()) { + Some([budget, used, ..]) => used < budget / 100 * room_percent(), + None => filled < WITHOUT_BUDGET, + } } -/// Smallest largest-dimension a texture may keep after a drop -/// (`VICTORY_TEXTURE_MIP_DROP_MIN_SIZE`, default 1024): smaller textures cost -/// little memory, and dropping them mostly costs UI/detail quality. +/// The share of the card's budget, in percent, up to which host copies of +/// textures picked by index are made ([`room`]): 90 unless +/// `VICTORY_TEXTURE_ROOM_PERCENT` says another (50 to 97). At 90 about a +/// tenth of the budget, 1,020 MB of 10,200, stays unused while thousands of +/// textures wait (runs 170-174); the card copies of title buffers from +/// 1 MiB up take 449 MB more of the card than before (941 against 492), +/// and 94 gives the textures about that much back. #[cfg(windows)] -fn mip_drop_floor() -> u64 { - static FLOOR: std::sync::OnceLock = std::sync::OnceLock::new(); - *FLOOR.get_or_init(|| { - std::env::var("VICTORY_TEXTURE_MIP_DROP_MIN_SIZE") +fn room_percent() -> u64 { + static PERCENT: std::sync::OnceLock = std::sync::OnceLock::new(); + *PERCENT.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_ROOM_PERCENT") .ok() .and_then(|v| v.trim().parse::().ok()) - .unwrap_or(1024) - .max(64) + .map_or(90, |percent| percent.clamp(50, 97)) }) } -/// How many of `requested` top mips may be dropped without touching render -/// targets, depth textures, UAVs, MSAA, non-power-of-two UI/artwork, small -/// textures or BC-misaligned mips. +/// For the card accounting line ([`card_accounting`]): the title texture +/// made for a view of memory at `address` with the resource description +/// `desc`, if there is one ([`texture_at`] makes it; this does not). #[cfg(windows)] -pub(crate) fn compute_mip_drop(desc: &ResourceDesc, requested: u32) -> u32 { - const TEXTURE_1D: u32 = 2; - if requested == 0 || desc.dimension == BUFFER || desc.flags & 0x7 != 0 || desc.sample_count > 1 - { - return 0; +pub(crate) fn placed_known(address: u64, desc: &[u32; 14]) -> Option { + // Without the filler words and with them: whichever `texture_at` keeps. + let mut key = *desc; + key[1] = 0; + key[13] = 0; + let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + map.get(&(address, key)).or_else(|| map.get(&(address, *desc))).map(|&r| r as This) +} + +/// For the card accounting line: whether title texture `this` has a host +/// copy now (2), had one that was let go and not made again (1), or never +/// had one (0); the bytes (its host copy's on the card, or without one +/// what its console layout takes in title memory); and where its title +/// memory is. `None` for buffers. Not a use of the texture. +#[cfg(windows)] +pub(crate) fn copy_state(this: This) -> Option<(u8, u64, u64)> { + use std::sync::atomic::Ordering::Relaxed; + if this.is_null() { + return None; + } + let r = resource(this); + if r.desc.dimension == BUFFER { + return None; } - let height = u64::from(desc.height); - let depth = u64::from(desc.depth_or_array_size); - if !desc.width.is_power_of_two() - || (desc.dimension != TEXTURE_1D && !height.is_power_of_two()) - || (desc.dimension == TEXTURE_3D && !depth.is_power_of_two()) + let memory = r.data() as u64; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + Some(match made.as_ref() { + Some((host, _)) => (2, host.bytes, memory), + None => (u8::from(r.host.gone.load(Relaxed)), footprint(&r.desc).map_or(0, |f| f.size), memory), + }) +} + +/// One line of where the card's memory is and what the queue of textures +/// picked by index would need (`VICTORY_CARD_ACCOUNTING=1`; `draw.rs` +/// `card_accounting` says when, and hands over the queue's side: `room` +/// as the pass found it, `due` its counts, `never` and `gone` the memory +/// of the due textures without a host copy). The line holds +/// - the host copies of textures the title fills that are alive: how +/// many, their bytes, and the bytes of the levels whose title memory is +/// not mapped (a host copy is made with every level of the description; +/// a texture streaming in has its small levels only). A copy's bytes +/// are shared out to its levels by their texels, so that part is an +/// estimate; +/// - the due slots: how many, and their textures by what they have on +/// the card (a host copy alive: no card memory needed; never one; one +/// that was let go), with the bytes the last two would need and how +/// much of their memory is mapped now; +/// - the host copies let go, made again and made since the line before. +/// +/// The textures are noted under the table's lock (their memory, their +/// description, their copy's bytes: about a millisecond for 18,000) and +/// the kernel is asked about their memory on a thread of its own, after +/// the lock is given back: one question for a texture that is all there +/// (up to 256 pages each; 18,000 textures of 5.5 GB are 1.4 million +/// pages, some 20,000 questions), one per level and array slice more for +/// one that is not. Not measured: a tenth to half a second is expected, +/// and the line says what it took. No line is begun while one is walking. +#[cfg(windows)] +pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, gone: Vec<(u64, u64)>) { + use std::sync::atomic::Ordering::Relaxed; + static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + // Host copies let go and their bytes, made again and their bytes, and + // made in all, at the line before. + static BEFORE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + if WALKING.swap(true, Relaxed) { + return; + } + let began = std::time::Instant::now(); + let mut copies: Vec<(usize, ResourceDesc, u64)> = Vec::new(); + // Textures the title fills without a host copy: never one, one let go. + let mut without = [0u64; 2]; { - return 0; + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + if !fills(&r.desc) { + continue; + } + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + match made.as_ref() { + Some((host, _)) => copies.push((r.data() as usize, r.desc, host.bytes)), + None => without[usize::from(r.host.gone.load(Relaxed))] += 1, + } + } } - let total_mips = mip_count(desc); - if total_mips <= 1 { - return 0; + let kinds = KINDS.each_ref().map(|k| k.load(Relaxed)); + let mut since = [0u64; 5]; + for ((slot, now), before) in since.iter_mut().zip([kinds[2], kinds[3], kinds[4], kinds[5], kinds[6]]).zip(&BEFORE) { + *slot = now.saturating_sub(before.swap(now, Relaxed)); } - let block = element(pc_format(desc.format)).map_or(1, |(_, block)| block); - let cap = requested.min(total_mips - 1); - let mut best = 0; - for drop in 1..=cap { - let width = (desc.width >> drop).max(1); - let height = if desc.dimension == TEXTURE_1D { - 1 - } else { - (height >> drop).max(1) + let video = crate::host::host().and_then(|h| h.video_memory()); + let noted_us = began.elapsed().as_micros() as u64; + let walk = move || { + fn texels(m: &texture::Mip) -> u64 { + u64::from(m.width) * u64::from(m.height) * u64::from(m.depth) + } + let began = std::time::Instant::now(); + // Copies; their bytes; the bytes of levels not mapped; copies with + // a level not mapped; with the largest level not mapped; with no + // level mapped; copies without a console layout (not asked). + let mut c = [0u64; 7]; + for &(memory, desc, bytes) in &copies { + c[0] += 1; + c[1] += bytes; + let Some(layout) = texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else { + c[6] += 1; + continue; + }; + if layout.size == 0 || crate::texture::committed(memory as *const u8, layout.size as usize) { + continue; + } + c[3] += 1; + // Every slice holds the whole chain: the levels of the tail in + // its first block, the others after it from the smallest up + // (`victory_formats::texture::Layout`). + let mips = &layout.mips; + let tail = (layout.first_tail_mip as usize).min(mips.len()); + let there = |from: u64, to: u64| { + (0..u64::from(layout.slices)).all(|slice| { + let at = memory as u64 + slice * layout.slice_size + from; + crate::texture::committed(at as *const u8, (to - from) as usize) + }) + }; + let all: u64 = mips.iter().map(texels).sum::().max(1); + let (mut missing, mut any) = (0u64, false); + for (level, m) in mips.iter().enumerate().take(tail) { + let end = if level == 0 { layout.slice_size } else { mips[level - 1].offset }; + if end <= m.offset { + continue; + } + if there(m.offset, end) { + any = true; + } else { + missing += texels(m); + c[4] += u64::from(level == 0); + } + } + if tail < mips.len() { + if there(0, layout.alignment.min(layout.slice_size).max(1)) { + any = true; + } else { + missing += mips[tail..].iter().map(texels).sum::(); + } + } + c[2] += (u128::from(bytes) * u128::from(missing) / u128::from(all)) as u64; + c[5] += u64::from(!any); + } + // Of the due textures without a host copy: how many; the bytes of + // their memory; with all of it mapped, and those bytes; with part + // of it mapped, and the bytes that are; with none of it mapped. + let mapped = |list: &[(u64, u64)]| { + let mut n = [0u64; 7]; + for &(at, len) in list { + n[0] += 1; + n[1] += len; + let there = crate::texture::mapped_bytes(at as *const u8, len as usize); + if len > 0 && there >= len { + n[2] += 1; + n[3] += len; + } else if there > 0 { + n[4] += 1; + n[5] += there; + } else { + n[6] += 1; + } + } + n }; - let depth = if desc.dimension == TEXTURE_3D { - (depth >> drop).max(1) - } else { - 1 + let (never, gone) = (mapped(&never), mapped(&gone)); + let [budget_mb, used_mb] = video.map_or([0, 0], |v| [v[0] >> 20, v[1] >> 20]); + let [copies_n, copies_mb, unmapped_mb, partly, largest, nothing, unknown] = + [c[0], c[1] >> 20, c[2] >> 20, c[3], c[4], c[5], c[6]]; + let [without_never, without_gone] = without; + let [due_slots, due_uploaded, due_other, alive_n, alive_mb] = [due[0], due[1], due[2], due[3], due[4] >> 20]; + let [never_n, never_mb, never_whole, never_whole_mb, never_part, never_part_mb, never_none] = + [never[0], never[1] >> 20, never[2], never[3] >> 20, never[4], never[5] >> 20, never[6]]; + let [gone_n, gone_mb, gone_whole, gone_whole_mb, gone_part, gone_part_mb, gone_none] = + [gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]]; + let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]]; + let walk_ms = began.elapsed().as_millis() as u64; + tracing::info!( + "card accounting: room {room}, the card {used_mb} MB in use of a budget of {budget_mb} MB; host copies of textures the title \ + fills: {copies_n} alive {copies_mb} MB, of which {unmapped_mb} MB are levels whose title memory is not mapped ({partly} copies \ + with such a level, {largest} of them the largest level, {nothing} with no level mapped; {unknown} without a console layout, not \ + asked); title textures without a host copy: {without_never} never had one, {without_gone} had one let go; due slots: \ + {due_slots} ({due_uploaded} uploaded before, {due_other} of nothing the title fills), their textures: {alive_n} with a host \ + copy alive ({alive_mb} MB, no card memory needed); {never_n} that never had one ({never_mb} MB of title memory: {never_whole} \ + all mapped {never_whole_mb} MB, {never_part} in part {never_part_mb} MB mapped, {never_none} not mapped); {gone_n} whose host \ + copy was let go ({gone_mb} MB: {gone_whole} all mapped {gone_whole_mb} MB, {gone_part} in part {gone_part_mb} MB mapped, \ + {gone_none} not mapped); since the line before: {let_go} host copies let go {let_go_mb} MB, {again} made again {again_mb} MB, \ + {made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own" + ); + WALKING.store(false, Relaxed); + }; + if std::thread::Builder::new().name("card accounting".into()).spawn(walk).is_err() { + WALKING.store(false, Relaxed); + } +} + +/// Lets go of the host copies of textures the title fills that nothing +/// names any more: placed textures were never released (one host texture +/// per address and description ever viewed: 18,639 of them, 2.5 GB, after +/// nine minutes of run 24), nor those of texture objects before the title +/// released them. A host copy goes when +/// - the title fills the texture ([`fills`]) and the host never copied +/// into it: its contents are in title memory; +/// - only the resource holds it: no list not yet reset names it (a list +/// holds the copies of the textures it uses, `HostList::transition`); +/// - only the host copy holds the host texture: no descriptor slot views +/// it (a slot keeps what it views, `HostHeap::kept`), so no shader can +/// read it through a slot made earlier, by a table or by an index; +/// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames. +/// +/// The next use makes the host copy anew and uploads the title's memory +/// again (its staging state goes with it). The title resource stays: its +/// address is what views and lists name. +/// shortcut: [`host_resource`] hands out the host texture without holding +/// it; a thread that asked for it and has not yet recorded its use (which +/// makes the list or the slot hold it) is protected by that idle time alone. +/// Every caller uses it at once, within the title's call. +/// Called before a submission starts, by the thread that submits. +/// `VICTORY_TEXTURE_SWEEP=0` lets nothing go. +#[cfg(windows)] +pub(crate) fn let_go_idle() { + use std::sync::atomic::Ordering::Relaxed; + const IDLE_FRAMES: u64 = 4; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { + return; + } + let idle_ms = crate::host::vram_idle_ms(crate::host::host().and_then(|h| h.video_memory())); + // For the trail (`crate::host::trail`): how many went, their bytes, + // and the first one. + let (mut went, mut bytes, mut first) = (0u64, 0u64, None); + let all = textures(); + for &at in all.iter() { + // SAFETY: a texture leaves the table before it is freed, under the + // lock held here (`Drop for Resource`). + let r = unsafe { &*(at as *const Resource) }; + if !fills(&r.desc) || crate::texture::host_wrote(at) { + continue; + } + let gone = { + let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + let idle = made.as_ref().is_some_and(|(host, _)| { + crate::host::long_ago(r.host.used.load(Relaxed), idle_ms, IDLE_FRAMES) + && std::sync::Arc::strong_count(host) == 1 + && crate::host::references(&host.texture) == 1 + }); + if idle { + // Under the lock: the next use must not find the staging + // state of the texture let go (it says "uploaded"). + crate::texture::unstage(at as This); + made.take() + } else { + None + } }; - let large_enough = width.max(height).max(depth) >= mip_drop_floor(); - let aligned = width.is_multiple_of(block) && height.is_multiple_of(block); - if large_enough && aligned { - best = drop; + if let Some((host, _)) = gone { + r.host.gone.store(true, Relaxed); + KINDS[2].fetch_add(1, Relaxed); + KINDS[3].fetch_add(host.bytes, Relaxed); + went += 1; + bytes += host.bytes; + if first.is_none() { + first = Some(at); + } + crate::host::retire(host); + } + } + if went > 0 { + crate::host::trail(|| { + format!( + "sweep: {went} host copies of textures the title fills let go ({} KiB), each held by its title texture alone (no list, no slot); the first: title texture {:#x}", + bytes >> 10, + first.unwrap_or(0) + ) + }); + } +} + +/// For the memory line: title textures with a host copy the host renders +/// to or writes and those copies' bytes (twins included); title textures +/// without a host copy and the bytes of title memory they are; host copies +/// of textures the title fills and their bytes; of all title textures, +/// the placed ones with a host copy; the bytes of the twins alone (the +/// layer's own: the console has no second texture for a depth texture +/// shaders write); and, of the host copies of placed textures the title +/// fills, the bytes of those whose title memory is not mapped any more and +/// of those a descriptor slot still shows (the card holds a texture the +/// title has given up for as long as a slot shows it). The last two are +/// estimates from every 16th such texture: asking Windows about the memory +/// of all 16,000 takes too long. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn census() -> [u64; 10] { + const EVERY: u64 = 16; + let mut count = [0u64; 10]; + let mut placed_filled = 0u64; + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + match made.as_ref() { + Some((host, twin)) => { + let kind = if host.filled { 4 } else { 0 }; + count[kind] += 1; + count[kind + 1] += host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes); + count[7] += twin.as_ref().map_or(0, |t| t.colour.bytes); + let placed = r.host.placed.load(std::sync::atomic::Ordering::Relaxed); + if placed { + count[6] += 1; + } + if placed && host.filled { + placed_filled += 1; + // Its first page: a texture's smallest mips lie there, + // and are mapped first and unmapped last. + if placed_filled.is_multiple_of(EVERY) && !crate::texture::committed(r.data().cast_const(), 1) { + count[8] += host.bytes * EVERY; + if crate::host::references(&host.texture) > 1 { + count[9] += host.bytes * EVERY; + } + } + } + } + None => { + count[2] += 1; + count[3] += footprint(&r.desc).map_or(0, |f| f.size); + } } } - best + count } -/// Shrinks `desc` to the mip that survives as host mip 0. +/// Host textures alive (the title's and the twins) and the bytes the host +/// gives them, for the memory line. #[cfg(windows)] -fn apply_mip_drop(desc: &mut ResourceDesc, title_mips: u32, drop: u32) { - const TEXTURE_1D: u32 = 2; - if drop == 0 { - return; +pub(crate) static HOST_TEXTURES: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The bytes the host allocates for `texture`. +#[cfg(windows)] +fn host_bytes(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> u64 { + let Some(host) = crate::host::host() else { + return 0; + }; + // SAFETY: plain queries on a live resource and device. + unsafe { + let desc = texture.GetDesc(); + host.device.GetResourceAllocationInfo(0, &[desc]).SizeInBytes } - desc.width = (desc.width >> drop).max(1); - if desc.dimension != TEXTURE_1D { - desc.height = (desc.height >> drop).max(1); +} + +#[cfg(windows)] +impl HostTexture { + fn new(texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32) -> HostTexture { + use std::sync::atomic::Ordering::Relaxed; + let bytes = host_bytes(&texture); + HOST_TEXTURES[0].fetch_add(1, Relaxed); + HOST_TEXTURES[1].fetch_add(bytes, Relaxed); + HostTexture { + texture, + state: std::sync::atomic::AtomicU32::new(state), + bytes, + filled: false, + } } - if desc.dimension == TEXTURE_3D { - desc.depth_or_array_size = (desc.depth_or_array_size >> drop).max(1); +} + +#[cfg(windows)] +impl Drop for HostTexture { + fn drop(&mut self) { + use std::sync::atomic::Ordering::Relaxed; + HOST_TEXTURES[0].fetch_sub(1, Relaxed); + HOST_TEXTURES[1].fetch_sub(self.bytes, Relaxed); + if self.filled { + KINDS[0].fetch_sub(1, Relaxed); + KINDS[1].fetch_sub(self.bytes, Relaxed); + } } - desc.mip_levels = u16::try_from(title_mips.saturating_sub(drop).max(1)).unwrap_or(1); +} + +/// How many textures placed in title memory have a resource of ours +/// (never released), for the memory line. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn placed_textures() -> u64 { + PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).len() as u64 } /// Moves the host texture to `wanted` (a host texture state); the host @@ -942,14 +1801,16 @@ fn apply_mip_drop(desc: &mut ResourceDesc, title_mips: u32, drop: u32) { #[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, _) = hosted(this, true)?; 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 now if +/// this is the texture's first use ([`Hosted`]). Asking is a use; what must +/// not count as one asks `host_made`. #[cfg(windows)] pub(crate) fn host_resource<'a>( this: This, @@ -957,7 +1818,13 @@ pub(crate) fn host_resource<'a>( if this.is_null() { return None; } - resource(this).host.as_deref().map(|h| &h.texture) + let (host, _) = hosted(this, true)?; + // SAFETY: the resource holds the host copy until the title releases it + // (lists and slots that name the texture hold it past that), or until + // `let_go_idle` takes it: only from a texture the title fills, that no + // list and no slot holds and that nothing asked for in seconds (the + // asking just made is noted under the same lock). + Some(unsafe { &*std::ptr::from_ref(&host.texture) }) } /// A title texture's host copy, shared, for a list to hold. @@ -966,7 +1833,7 @@ pub(crate) fn host_copy(this: This) -> Option> { if this.is_null() { return None; } - resource(this).host.clone() + hosted(this, true).map(|made| made.0) } /// A host texture like the title's: same description, in GPU memory, @@ -976,7 +1843,7 @@ fn host_texture( desc: &ResourceDesc, state: u32, clear: *const c_void, -) -> Option<(windows::Win32::Graphics::Direct3D12::ID3D12Resource, u32)> { +) -> Option { use windows::Win32::Graphics::Direct3D12::*; const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access if desc.dimension == BUFFER { @@ -988,15 +1855,22 @@ fn host_texture( d.alignment = 0; d.flags &= PC_FLAGS; // PC refuses depth targets that are also unordered-access (the console - // allows both; Grand Theft Auto VI's shadow maps ask for it). - // shortcut: the host copy loses UAV use; give it a second view-only - // copy if draws write it as a UAV. + // allows both; the title's shadow maps ask for it). + // The host copy loses the unordered access: shaders write a colour + // twin instead ([`Twin`]). const DEPTH: u32 = 2; const UNORDERED: u32 = 4; if d.flags & DEPTH != 0 { + if d.flags & UNORDERED != 0 { + DEPTH_UNORDERED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } d.flags &= !UNORDERED; } d.format = pc_format(d.format); + const TARGET: u32 = 1; + if d.flags & (TARGET | UNORDERED) != 0 { + d.format = target_format(d.format); + } const DENY_SHADER_RESOURCE: u32 = 8; if d.flags & DENY_SHADER_RESOURCE == 0 && let Some(&(_, typeless)) = DEPTH_FORMATS.iter().find(|&&(f, _)| f == d.format) @@ -1008,113 +1882,49 @@ fn host_texture( if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) { d.format = family(d.format); } - // Some console formats (such as B5G5R5A1_UNORM) allow unordered access - // or render-target flags on the console that PC GPUs refuse; drop - // unsupported flags on typed formats so the host copy is still created. - const RENDER_TARGET: u32 = 1; - let typeless = family(d.format) == d.format && family(d.format + 1) == d.format; - if !typeless && d.flags & (RENDER_TARGET | UNORDERED) != 0 { - let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { - Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(d.format as i32), - ..Default::default() - }; - // SAFETY: plain feature query into our struct. - let ok = unsafe { - host.device.CheckFeatureSupport( - D3D12_FEATURE_FORMAT_SUPPORT, - (&raw mut support).cast(), - size_of::() as u32, - ) - } - .is_ok(); - if ok { - if d.flags & UNORDERED != 0 - && support.Support1.0 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0 == 0 - { - d.flags &= !UNORDERED; - } - if d.flags & RENDER_TARGET != 0 - && support.Support1.0 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0 == 0 - { - d.flags &= !RENDER_TARGET; - } - } - } // The clear value names the format too: format, then color or depth - // and stencil (5 words). D3D12 requires a null optimized clear value - // when neither render-target nor depth-stencil is set (id=815). - let clear_value = (!clear.is_null() && d.flags & (RENDER_TARGET | DEPTH) != 0).then(|| { + // and stencil (5 words). + let clear_value = (!clear.is_null()).then(|| { // SAFETY: the title passes a whole clear value. let mut value = unsafe { clear.cast::<[u32; 5]>().read_unaligned() }; value[0] = pc_format(value[0]); + if d.flags & (TARGET | UNORDERED) != 0 { + value[0] = target_format(value[0]); + } value }); - let title_mips = mip_count(desc); - let base = d; - let mut drop = compute_mip_drop(&base, requested_mip_drop()); - apply_mip_drop(&mut d, title_mips, drop); let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; - let mut texture = None; - let made = loop { - let mut attempt = None; - // SAFETY: the description has the host layout (checked size, same - // fields); the out pointer is ours. - let made = unsafe { - host.device.CreateCommittedResource( - &heap, - D3D12_HEAP_FLAG_NONE, - (&raw const d).cast(), - D3D12_RESOURCE_STATES(crate::host::legal_for( - d.flags, - crate::host::texture_state(state), - ) as i32), - // The same layout: format, then color or depth and stencil. - clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), - &mut attempt, - ) - }; - if made.is_ok() { - texture = attempt; - break made; - } - let Err(e) = &made else { unreachable!() }; - if e.code().0 != E_OUTOFMEMORY || drop >= MAX_MIP_DROP { - break made; - } - let pressure = OOM_MIP_PRESSURE - .fetch_max(drop + 1, std::sync::atomic::Ordering::Relaxed) - .max(drop + 1); - let next = compute_mip_drop(&base, requested_mip_drop().max(pressure)); - if next <= drop { - break made; - } - drop = next; - d = base; - apply_mip_drop(&mut d, title_mips, drop); - tracing::warn!( - drop, - "host texture allocation out of memory; dropping another top mip" - ); + let mut texture: Option = None; + // SAFETY: the description has the host layout (checked size, same + // fields); the out pointer is ours. + let made = unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES( + crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, + ), + // The same layout: format, then color or depth and stencil. + clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), + &mut texture, + ) }; if let Err(e) = made { - tracing::warn!(error = %e, desc = ?d, drop, "no host texture"); + tracing::warn!(error = %e, desc = ?d, "no host texture"); } if let Some(t) = &texture { crate::host::name(t, || { - format!( - "texture {}x{} f{} flags {:#x}", - d.width, d.height, d.format, d.flags - ) + format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags) }); } - texture.map(|texture| (texture, drop)) + texture } /// A texture's console memory and description; `None` for buffers. -#[cfg(windows)] pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> { if this.is_null() { return None; @@ -1168,8 +1978,6 @@ fn hand_out_resource( ) -> HRESULT { #[cfg(not(windows))] let _ = (state, clear); - #[cfg(windows)] - let host = host_texture(&desc, state, clear); let resource = Box::new(Resource { object: Object::new(&RESOURCE_FUNCTIONS), desc, @@ -1177,17 +1985,33 @@ fn hand_out_resource( heap_flags, backing, #[cfg(windows)] - host: host.map(|(texture, mip_drop)| { - let state = crate::host::legal_state(&texture, crate::host::texture_state(state)); - std::sync::Arc::new(HostTexture { - texture, - state: state.into(), - title_mips: mip_count(&desc), - mip_drop, - is_3d: desc.dimension == TEXTURE_3D, - }) - }), + host: Hosted { + made: std::sync::Mutex::new(None), + state, + // SAFETY: the title passes a whole clear value (the format, + // then color or depth and stencil: 5 words) or null. + clear: (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read_unaligned() }), + used: std::sync::atomic::AtomicU64::new(0), + refused: std::sync::atomic::AtomicBool::new(false), + gone: std::sync::atomic::AtomicBool::new(false), + placed: std::sync::atomic::AtomicBool::new(false), + }, }); + // The host copy waits for the texture's first use ([`Hosted`]). + #[cfg(windows)] + if desc.dimension != BUFFER { + let at = std::ptr::from_ref::(&resource) as usize; + textures().insert(at); + if !fills(&desc) { + TARGETS_AT + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(resource.data() as u64, at); + } + if !lazy() { + let _ = hosted(at as This, true); + } + } #[cfg(windows)] if desc.dimension == BUFFER { let at = std::ptr::from_ref::(&resource) as usize; @@ -1199,11 +2023,28 @@ fn hand_out_resource( #[cfg(windows)] impl Drop for Resource { fn drop(&mut self) { - #[cfg(feature = "diagnostics")] - if self + // Out of the table of textures first: the sweep looks at the ones + // in it, under its lock. + if self.desc.dimension != BUFFER { + textures().remove(&(std::ptr::from_ref::(self) as usize)); + if !fills(&self.desc) { + let mut targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner()); + let at = self.data() as u64; + if targets.get(&at) == Some(&(std::ptr::from_ref::(self) as usize)) { + targets.remove(&at); + } + } + } + let made = self .host + .made + .get_mut() + .unwrap_or_else(|e| e.into_inner()) + .take(); + #[cfg(feature = "diagnostics")] + if made .as_ref() - .is_some_and(|h| std::sync::Arc::strong_count(h) > 1) + .is_some_and(|(h, _)| std::sync::Arc::strong_count(h) > 1) { // Before lists held their textures, this freed a texture that // lists not yet run still named (a GPU page fault). @@ -1217,6 +2058,14 @@ impl Drop for Resource { ); } } + // A running submission may still read the host copy (and a depth + // texture's colour twin). + if let Some((host, twin)) = made { + crate::host::retire(host); + if let Some(twin) = twin { + crate::host::retire(twin); + } + } crate::texture::forget(std::ptr::from_ref::(self) as usize); crate::descriptor::forget(std::ptr::from_ref::(self) as usize); if self.desc.dimension == BUFFER { @@ -1268,7 +2117,7 @@ pub(crate) extern "system" fn create_committed( ) } -/// Device method 0x3f8, inferred from Grand Theft Auto VI's calls +/// Device method 0x3f8, inferred from the title's calls /// (title+0x193e1b4: its back buffers, heap flag "allow display"): the /// committed resource creation of the enhanced-barrier interfaces, /// `(heap, heap flags, desc1, initial layout, clear value, protected @@ -1331,7 +2180,7 @@ pub(crate) extern "system" fn unregister_page_pool(_: This, handle: usize) -> HR } /// Device method 0x428, one of the `ID3D12Device9` to `ID3D12Device11` -/// additions. From Grand Theft Auto VI's call: a resource at a virtual +/// additions. From the title's call: a resource at a virtual /// address the title mapped itself, `(address, desc1, initial barrier /// layout, clear value, iid, out)`, as `CreatePlacedResourceX` with /// enhanced barriers. GPU addresses are CPU addresses, so the resource is @@ -1381,36 +2230,95 @@ pub(crate) extern "system" fn create_at_address( } /// Textures the title placed in its own memory and views without a -/// resource object (device 0x230, Grand Theft Auto VI's streamed and +/// resource object (device 0x230, the title's streamed and /// interface textures), by address and description: a resource at that /// address, made the first time a draw reads one. -/// shortcut: never released (one host texture per distinct address and -/// description viewed); release them when the title unmaps or reuses the -/// memory once streaming grows VRAM use. +/// The resource is kept for the run (views and lists name its address); +/// its host texture is let go when nothing names it any more +/// ([`let_go_idle`]) and made again on the next use. #[cfg(windows)] static PLACED_TEXTURES: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); -/// The number and estimated allocation size of placed textures retained by the cache. +/// The placed textures asked for with filler words set, as asked +/// (address and description): for [`PLACED_TWINS`]. +#[cfg(windows)] +static PLACED_RAW: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); + +/// Placed textures asked for a second time with other filler words in +/// their description: each was a second resource and host copy before the +/// filler was left out of the key ([`texture_at`]). +#[cfg(windows)] +static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// See [`PLACED_TWINS`]. #[cfg(all(windows, feature = "diagnostics"))] -pub(crate) fn placed_texture_cache_stats() -> (usize, u64) { - PLACED_TEXTURES - .lock() - .unwrap_or_else(|e| e.into_inner()) - .keys() - .fold((0, 0), |(count, bytes), &(_, words)| { - // SAFETY: the cache key stores the original 56-byte resource description. - let desc = unsafe { words.as_ptr().cast::().read_unaligned() }; - let size = footprint(&desc).map_or(0, |info| info.size); - (count + 1, bytes.saturating_add(size)) - }) +pub(crate) fn placed_filler_twins() -> u64 { + PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The bytes of title memory a texture with the resource description +/// `desc` (as words) takes where the title placed it; `None` for a buffer +/// and for a description without a size. +#[cfg(windows)] +pub(crate) fn placed_bytes(desc: &[u32; 14]) -> Option { + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::().read_unaligned() }; + if d.dimension == BUFFER { + return None; + } + footprint(&d).map(|f| f.size) +} + +/// The resource [`texture_at`] made for a texture placed at `address` with +/// the description `desc`, if it has made one: never made here (for the +/// frame listing, which must not count as a use). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option { + let mut key = *desc; + key[1] = 0; + key[13] = 0; + let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + let found = map.get(&(address, key)).or_else(|| map.get(&(address, *desc)))?; + Some(*found as This) } /// The resource for a texture placed at `address` with the resource /// description `desc` (as words), made on first use. #[cfg(windows)] pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { + // Words 1 and 13 of the description are the filler of its layout + // (after the dimension, and at the end): the title leaves there what + // its stack held, and two views of one texture that differed only in + // them each got a resource and a host copy of their own, on a card + // that fills at world entry. They are not part of what a texture is. + // `VICTORY_PLACED_FILLER=1`: kept in the key, as before. + static KEPT: std::sync::OnceLock = std::sync::OnceLock::new(); + let raw = *desc; + let mut key = *desc; + if !*KEPT.get_or_init(|| std::env::var_os("VICTORY_PLACED_FILLER").is_some_and(|v| v == "1")) { + key[1] = 0; + key[13] = 0; + } + let desc = &key; let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + // How many resources the filler alone would have added (a count for + // the log: `placed_filler_twins`). + if raw != key { + let mut seen = PLACED_RAW.lock().unwrap_or_else(|e| e.into_inner()); + if seen.insert((address, raw)) { + let others = seen.range((address, [0; 14])..=(address, [u32::MAX; 14])).filter(|(_, r)| { + let mut blank = *r; + blank[1] = 0; + blank[13] = 0; + blank == key + }); + if others.count() > 1 { + PLACED_TWINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + } if let Some(&r) = map.get(&(address, *desc)) { return Some(r as This); } @@ -1433,7 +2341,12 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { return None; } map.insert((address, *desc), out as usize); - resource(out).host.is_some().then_some(out) + crate::texture::placed_in_host_written(address, desc); + resource(out) + .host + .placed + .store(true, std::sync::atomic::Ordering::Relaxed); + Some(out) } pub(crate) extern "system" fn create_placed( @@ -1717,7 +2630,7 @@ mod tests { slot::(device, 0xd0)(&mut p, device, 1, 1); assert_eq!(p.cpu_pages, 1, "default: not CPU-visible"); - // 0x428: a buffer over memory the title owns, as GTA VI asks. + // 0x428: a buffer over memory the title owns, as the title asks. type At = extern "system" fn( This, u64, @@ -2042,6 +2955,684 @@ mod tests { } } + /// A 16-bit depth texture the title also asks unordered access for gets + /// a colour twin, and the host copies one into the other, both ways: a + /// pattern put into the twin is copied to the depth texture, the twin + /// is overwritten with zeros, and the pattern comes back from the depth + /// texture. A copy the host does not allow ends the test (with the + /// debug layer's message under `VICTORY_D3D12_DEBUG=1` in a diagnostics + /// build). + #[cfg(windows)] + #[test] + fn a_depth_texture_and_its_twin_copy_into_each_other() { + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + const DEPTH_WRITE: u32 = 0x10; + let desc = ResourceDesc { + flags: 6, + ..texture(4, 4, 55, 1) + }; + let mut depth = null; + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &desc, + DEPTH_WRITE, + null.cast(), + &RESOURCE_IIDS[0], + &mut depth + ), + S_OK + ); + let host_depth = host_resource(depth).unwrap(); + let Some(twin) = twin_resource(depth) else { + return; // twins are turned off + }; + // SAFETY: live resources. + let (d, t) = unsafe { (host_depth.GetDesc(), twin.GetDesc()) }; + // Both R16 typeless: one a depth texture, one with unordered access. + assert_eq!((d.Format.0, d.Flags.0), (53, 2)); + assert_eq!((t.Format.0, t.Flags.0), (53, 4)); + + // Four rows of four 16-bit texels, 256 bytes apart as copies place + // them: the pattern, then as many zeros. + let mut pattern = vec![0u8; 1024]; + for row in 0..4 { + for b in 0..8 { + pattern[row * 256 + b] = (1 + row * 8 + b) as u8; + } + } + let (upload, data) = host.upload_buffer(2048).unwrap(); + // SAFETY: the buffer's mapping, 2048 bytes. + unsafe { + std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024); + std::ptr::write_bytes(data.add(1024), 0, 1024); + } + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + // SAFETY: plain creation of a readback buffer. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + + // A texture's one subresource; the four rows of a buffer at `offset`. + let whole = |texture: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let rows = |buffer: &ID3D12Resource, offset: u64| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(53), + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let (written, tested, source, dest) = ( + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let moved = crate::host::transition; + let list = host.new_list().unwrap(); + // SAFETY: an open list and live resources; the two textures are one + // size in one format family. + unsafe { + let l = &list.list; + // The pattern into the twin, the twin into the depth texture. + l.ResourceBarrier(&[moved(twin, written, dest), moved(host_depth, tested, dest)]); + l.CopyTextureRegion(&whole(twin), 0, 0, 0, &rows(&upload, 0), None); + l.ResourceBarrier(&[moved(twin, dest, source)]); + l.CopyResource(host_depth, twin); + // Zeros over the twin, then the depth texture back into it. + l.ResourceBarrier(&[moved(twin, source, dest)]); + l.CopyTextureRegion(&whole(twin), 0, 0, 0, &rows(&upload, 1024), None); + l.ResourceBarrier(&[moved(host_depth, dest, source)]); + l.CopyResource(twin, host_depth); + // The twin read back; both textures to the states they had. + l.ResourceBarrier(&[moved(twin, dest, source)]); + l.CopyTextureRegion(&rows(&readback, 0), 0, 0, 0, &whole(twin), None); + l.ResourceBarrier(&[ + moved(twin, source, written), + moved(host_depth, source, tested), + ]); + } + list.close(); + host.execute(&[&list]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copies finished (execute waits); the buffer is 1024 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 1024, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::(), 1024) + }; + for row in 0..4 { + let at = row * 256; + assert_eq!(read[at..at + 8], pattern[at..at + 8], "row {row}"); + } + } + + /// A depth texture with a stencil plane that the title also asks + /// unordered access for gets a twin of the stencil plane, and what + /// shaders write there is in the stencil plane once the list is closed: + /// a pattern put into the twin is read back from the plane. + #[cfg(windows)] + #[test] + fn a_stencil_planes_twin_reaches_the_plane() { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + const DEPTH_WRITE: u32 = 0x10; + let desc = ResourceDesc { + flags: 6, + ..texture(4, 4, 45, 1) + }; + let mut depth = null; + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &desc, + DEPTH_WRITE, + null.cast(), + &RESOURCE_IIDS[0], + &mut depth + ), + S_OK + ); + let host_depth = host_resource(depth).unwrap(); + let Some(twin) = twin_resource(depth) else { + return; // twins are turned off + }; + // SAFETY: live resources. + let (d, t) = unsafe { (host_depth.GetDesc(), twin.GetDesc()) }; + // R24G8 typeless with depth, R8 typeless with unordered access. + assert_eq!((d.Format.0, d.Flags.0), (44, 2)); + assert_eq!((t.Format.0, t.Flags.0), (60, 4)); + + // Four rows of four texels, 256 bytes apart as copies place them. + let mut pattern = vec![0u8; 1024]; + for row in 0..4 { + for b in 0..4 { + pattern[row * 256 + b] = (1 + row * 4 + b) as u8; + } + } + let (upload, data) = host.upload_buffer(1024).unwrap(); + // SAFETY: the buffer's mapping, 1024 bytes. + unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024) }; + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + // Room for the rows as the host places them (512 bytes apart + // for the stencil plane on NVIDIA, not 256). + Width: 4096, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + // SAFETY: plain creation of a readback buffer. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + // How the host lays the stencil plane (subresource 1) out in a buffer. + let mut plane = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + // SAFETY: a plain query writing one footprint. + unsafe { + host.device + .GetCopyableFootprints(&d, 1, 1, 0, Some(&mut plane), None, None, None); + } + let pattern_rows = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(60), + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }; + + // A subresource of a texture; rows of a buffer. + let whole = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: index, + }, + }; + let rows = |buffer: &ID3D12Resource, placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: placed, + }, + } + }; + let (written, source, dest) = ( + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let moved = crate::host::transition; + + // The pattern into the twin, where a shader would write it. + let fill = host.new_list().unwrap(); + // SAFETY: an open list and live resources. + unsafe { + let l = &fill.list; + l.ResourceBarrier(&[moved(twin, written, dest)]); + l.CopyTextureRegion(&whole(twin, 0), 0, 0, 0, &rows(&upload, pattern_rows), None); + l.ResourceBarrier(&[moved(twin, dest, written)]); + } + fill.close(); + host.execute(&[&fill]); + + // A list in which a shader writes the twin: closing it copies the + // twin into the stencil plane. + let list = host.new_list().unwrap(); + assert!(list.twin_use(depth, true, true)); + list.twins_written(); + list.close(); + host.execute(&[&list]); + + // The stencil plane read back from the state the list left it in. + let state = host_copy(depth).unwrap().state.load(Relaxed); + let state = D3D12_RESOURCE_STATES(state as i32); + let back = host.new_list().unwrap(); + // SAFETY: an open list and live resources; a whole subresource. + unsafe { + let l = &back.list; + l.ResourceBarrier(&[moved(host_depth, state, source)]); + let (to, from) = (rows(&readback, plane), whole(host_depth, 1)); + l.CopyTextureRegion(&to, 0, 0, 0, &from, None); + l.ResourceBarrier(&[moved(host_depth, source, state)]); + } + back.close(); + host.execute(&[&back]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copies finished (execute waits); the buffer is 4096 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 4096, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::(), 4096) + }; + let pitch = plane.Footprint.RowPitch as usize; + for row in 0..4 { + let (at, from) = (row * pitch, row * 256); + assert_eq!(read[at..at + 4], pattern[from..from + 4], "row {row}"); + } + } + + /// The depth plane of a depth-stencil texture is drawn from the plane's + /// twin when the list that wrote the twin closes: class numbers are put + /// into the twin of a texture in the console's 16-bit depth-stencil + /// format, and draws with the depth test "equal" at the depth the + /// title's lighting computes for a class (the number times the float + /// nearest 1/65535) then cover the texels of that class and no other. + #[cfg(windows)] + #[test] + fn a_depth_planes_twin_is_drawn_into_the_plane() { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + use windows::core::s; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + const DEPTH_WRITE: u32 = 0x10; + let desc = ResourceDesc { + flags: 6, + ..texture(4, 4, 118, 1) + }; + let mut depth = null; + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &desc, + DEPTH_WRITE, + null.cast(), + &RESOURCE_IIDS[0], + &mut depth + ), + S_OK + ); + let host_depth = host_resource(depth).unwrap(); + let Some(plane) = twin_plane_resource(depth) else { + return; // these twins are turned off + }; + // SAFETY: live resources. + let (d, t) = unsafe { (host_depth.GetDesc(), plane.GetDesc()) }; + // R24G8 typeless with depth, R16 typeless with unordered access. + assert_eq!((d.Format.0, d.Flags.0), (44, 2)); + assert_eq!((t.Format.0, t.Flags.0), (53, 4)); + + // Four rows of four class numbers (16 bits each), 256 bytes apart + // as copies place them. 128 and 129 are the classes whose 24-bit + // depth lies nearest a half step. + const CLASSES: [u16; 16] = [ + 8, 65, 128, 129, 65, 8, 129, 128, 0, 255, 65, 64, 129, 130, 8, 65, + ]; + let mut pattern = vec![0u8; 1024]; + for (i, class) in CLASSES.into_iter().enumerate() { + let at = i / 4 * 256 + i % 4 * 2; + pattern[at..at + 2].copy_from_slice(&class.to_le_bytes()); + } + let (upload, data) = host.upload_buffer(1024).unwrap(); + // SAFETY: the buffer's mapping, 1024 bytes. + unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024) }; + let buffer = |kind: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut made: Option = None; + // SAFETY: plain creation of a buffer. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + state, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() + }; + let readback = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + // The colour target the draws cover: 4x4, 8 bits a texel. + let target = { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 4, + Height: 4, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(61), + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut made: Option = None; + // SAFETY: plain creation of a texture. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() + }; + let rows_of = |format: i32| D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(format), + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }; + // A texture's one subresource; rows of a buffer. + let whole = |texture: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let rows = |buffer: &ID3D12Resource, placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: placed, + }, + } + }; + let (written, source, dest, tested, drawn) = ( + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_RENDER_TARGET, + ); + let moved = crate::host::transition; + + // The class numbers into the twin, where a shader would write them. + let fill = host.new_list().unwrap(); + // SAFETY: an open list and live resources. + unsafe { + let l = &fill.list; + l.ResourceBarrier(&[moved(plane, written, dest)]); + l.CopyTextureRegion(&whole(plane), 0, 0, 0, &rows(&upload, rows_of(53)), None); + l.ResourceBarrier(&[moved(plane, dest, written)]); + } + fill.close(); + host.execute(&[&fill]); + + // A list in which a shader writes the twins: closing it draws the + // depth plane's twin into the plane. + let list = host.new_list().unwrap(); + assert!(list.twin_use(depth, true, true)); + list.twins_written(); + list.close(); + host.execute(&[&list]); + + // The draws: a triangle over the target at the depth of a class, + // as the title's lighting places its rectangles. + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants = 1, b0)" +cbuffer Drawn : register(b0) { uint number; }; +[RootSignature(RS)] +float4 corner(uint i : SV_VertexID) : SV_Position { + float z = float(number) * asfloat(0x37800080); + return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, z, 1.0); +} +float4 lit() : SV_Target { return 1.0; } +"#; + let vs = crate::host::compile(SOURCE, s!("corner"), s!("vs_5_1")).unwrap(); + let ps = crate::host::compile(SOURCE, s!("lit"), s!("ps_5_1")).unwrap(); + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = 0xf; + let mut formats = [DXGI_FORMAT(0); 8]; + formats[0] = DXGI_FORMAT(61); + // SAFETY: plain creation; the description points at live data. + let (signature, pipeline) = unsafe { + let signature: ID3D12RootSignature = + host.device.CreateRootSignature(0, &vs[..]).unwrap(); + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&signature), + VS: code(&vs[..]), + PS: code(&ps[..]), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // As the title's lighting: test "equal", nothing written. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_EQUAL, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: formats, + DSVFormat: DXGI_FORMAT(45), + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = + host.device.CreateGraphicsPipelineState(&desc).unwrap(); + (signature, pipeline) + }; + let state = host_copy(depth).unwrap().state.load(Relaxed); + let state = D3D12_RESOURCE_STATES(state as i32); + let colour = host.rtv(Some(&target), None); + let depth_view = host.dsv( + host_depth, + Some(&D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT(45), + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + ..Default::default() + }), + ); + let back = host.new_list().unwrap(); + // SAFETY: an open list and live resources and views. + unsafe { + let l = &back.list; + if state != tested { + l.ResourceBarrier(&[moved(host_depth, state, tested)]); + } + l.ClearRenderTargetView(colour, &[0.0; 4], None); + l.SetGraphicsRootSignature(&signature); + l.SetPipelineState(&pipeline); + l.OMSetRenderTargets(1, Some(&colour), false, Some(&depth_view)); + l.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: 4.0, + Height: 4.0, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + l.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: 4, + bottom: 4, + }]); + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4)); + // Classes 65 and 129 are drawn; the others are not. + for class in [65u32, 129] { + l.SetGraphicsRoot32BitConstant(0, class, 0); + l.DrawInstanced(3, 1, 0, 0); + } + l.ResourceBarrier(&[moved(&target, drawn, source)]); + let (to, from) = (rows(&readback, rows_of(61)), whole(&target)); + l.CopyTextureRegion(&to, 0, 0, 0, &from, None); + } + back.close(); + host.execute(&[&back]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copy finished (execute waits); the buffer is 1024 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 1024, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::(), 1024) + }; + for (i, class) in CLASSES.into_iter().enumerate() { + let covered = read[i / 4 * 256 + i % 4] != 0; + let drawn = matches!(class, 65 | 129); + assert_eq!(covered, drawn, "texel {i}, class {class}"); + } + } + #[test] fn committed_and_placed_resources_map_at_their_gpu_address() { let null = std::ptr::null(); @@ -2100,127 +3691,4 @@ mod tests { assert_eq!(slot::(heap, 0x10)(heap), 1); assert_eq!(slot::(placed, 0x10)(placed), 0); } - - #[cfg(windows)] - #[test] - fn host_texture_drops_unsupported_uav_flag_for_b5g5r5a1() { - use windows::Win32::Graphics::Direct3D12::*; - if crate::host::host().is_none() { - return; // no host GPU here - } - let make = |format: u32, flags: u32| ResourceDesc { - dimension: 3, // TEXTURE2D - alignment: 0, - width: 64, - height: 64, - depth_or_array_size: 1, - mip_levels: 1, - format, - sample_count: 1, - sample_quality: 0, - layout: 0, - flags, - }; - // B5G5R5A1_UNORM (86) with ALLOW_RENDER_TARGET | ALLOW_UNORDERED_ACCESS (5): - // the flag must survive exactly when the host reports typed-UAV - // support for the format and be dropped otherwise. - let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { - Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(86), - ..Default::default() - }; - let host = crate::host::host().unwrap(); - // SAFETY: plain feature query into our struct. - let typed_uav = unsafe { - host.device.CheckFeatureSupport( - D3D12_FEATURE_FORMAT_SUPPORT, - (&raw mut support).cast(), - size_of::() as u32, - ) - } - .is_ok() - && support.Support1.0 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0 != 0; - let b5g5r5a1 = host_texture(&make(86, 5), 0, std::ptr::null()) - .map(|(texture, _)| texture) - .expect("B5G5R5A1_UNORM texture should be created"); - // SAFETY: live D3D12 resource. - let d = unsafe { b5g5r5a1.GetDesc() }; - assert_eq!( - d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0, - if typed_uav { - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 - } else { - 0 - } - ); - assert_ne!(d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0, 0); - - // B4G4R4A4_UNORM (115) with ALLOW_RENDER_TARGET (1) and a non-null - // clear value: the flag must survive exactly when the host reports - // render-target support for the format and be dropped otherwise. - let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { - Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(115), - ..Default::default() - }; - // SAFETY: plain feature query into our struct. - let render_target = unsafe { - host.device.CheckFeatureSupport( - D3D12_FEATURE_FORMAT_SUPPORT, - (&raw mut support).cast(), - size_of::() as u32, - ) - } - .is_ok() - && support.Support1.0 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0 != 0; - let clear = [115u32, 0, 0, 0, 0]; - let b4g4r4a4 = host_texture(&make(115, 1), 0, clear.as_ptr().cast()) - .map(|(texture, _)| texture) - .expect("B4G4R4A4_UNORM texture should succeed"); - // SAFETY: live D3D12 resource. - let bd = unsafe { b4g4r4a4.GetDesc() }; - assert_eq!( - bd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0, - if render_target { - D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 - } else { - 0 - } - ); - - // R8G8B8A8_TYPELESS (27) with flags=5 must keep ALLOW_UNORDERED_ACCESS. - let typeless = host_texture(&make(27, 5), 0, std::ptr::null()) - .map(|(texture, _)| texture) - .expect("R8G8B8A8_TYPELESS texture should succeed"); - // SAFETY: live D3D12 resource. - let td = unsafe { typeless.GetDesc() }; - assert_ne!(td.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0, 0); - } - - #[cfg(windows)] - #[test] - fn mip_drop_eligibility_and_subresource_remapping() { - let tex2d = |width, height, mips, format, flags| ResourceDesc { - dimension: 3, - alignment: 0, - width, - height, - depth_or_array_size: 1, - mip_levels: mips, - format, - sample_count: 1, - sample_quality: 0, - layout: 0, - flags, - }; - assert_eq!(compute_mip_drop(&tex2d(2048, 2048, 0, 28, 0), 1), 1); - assert_eq!(compute_mip_drop(&tex2d(1024, 1024, 0, 28, 0), 2), 0); - assert_eq!(compute_mip_drop(&tex2d(1920, 1080, 0, 28, 0), 1), 0); - assert_eq!(compute_mip_drop(&tex2d(2048, 2048, 0, 28, 1), 1), 0); - assert_eq!(compute_mip_drop(&tex2d(2048, 2048, 1, 28, 0), 1), 0); - assert_eq!(remap_subresource(0, 11, 2, false), None); - assert_eq!(remap_subresource(2, 11, 2, false), Some(0)); - assert_eq!(remap_subresource(13, 11, 2, false), Some(9)); - assert_eq!(remap_subresource(4, 11, 0, false), Some(4)); - assert_eq!(remap_subresource(2, 11, 2, true), Some(0)); - assert_eq!(remap_subresource(1, 11, 2, true), None); - } } diff --git a/crates/victory-gpu/src/root.rs b/crates/victory-gpu/src/root.rs index 39b4f0d..5bded71 100644 --- a/crates/victory-gpu/src/root.rs +++ b/crates/victory-gpu/src/root.rs @@ -52,8 +52,6 @@ type SerializeVersioned = /// An export of the host's `d3d12.dll` in System32, looked up once. fn host_export(cache: &OnceLock>, name: &CStr) -> Option { - #[cfg(not(windows))] - let _ = name; *cache.get_or_init(|| { #[cfg(windows)] { @@ -149,17 +147,14 @@ type Deserialize = /// `d3d12_xs!D3D12CreateRootSignatureDeserializer`: our blobs are the /// host's serialization, so the host's deserializer reads them, and its /// object (IUnknown, then the description getter) is laid out as the -/// console's. Grand Theft Auto VI's upscaler asks with the PC interface id. +/// console's. The title's upscaler asks with the PC interface id. pub extern "system" fn create_deserializer( blob: *const u8, size: usize, iid: *const Iid, out: *mut *mut c_void, ) -> HRESULT { - // The host dereferences the interface id without checking it, so a null - // one is answered here instead of crashing there; an empty blob is - // malformed and rejected the same way. - if blob.is_null() || size == 0 || iid.is_null() || out.is_null() { + if blob.is_null() || out.is_null() { return E_INVALIDARG; } static FUNCTION: OnceLock> = OnceLock::new(); @@ -219,221 +214,8 @@ static FUNCTIONS: Table<24> = { #[cfg(test)] mod tests { - #[cfg(windows)] use super::*; - #[cfg(windows)] - use crate::object::{E_NOINTERFACE, E_POINTER, S_FALSE, S_OK, slot}; - - /// An interface we do not implement. - const OTHER_IID: Iid = guid(0x5a5a_5a5a, 0x5a5a, 0x5a5a, [0x5a; 8]); - - /// The shim hands the blob to the host unchanged; `create` keeps it, so - /// any bytes serve. - const BLOB: [u8; 4] = [0x01, 0x02, 0x03, 0x04]; - - fn created(iid: &Iid) -> This { - let mut out = std::ptr::null(); - let hr = create( - std::ptr::null(), - 0, - BLOB.as_ptr(), - BLOB.len(), - iid, - &mut out, - ); - assert_eq!(hr, S_OK); - assert!(!out.is_null()); - out - } - - /// The host's structures, field for field (64-bit layout). - #[cfg(target_pointer_width = "64")] - #[test] - fn descriptions_keep_the_pc_layout() { - assert_eq!(std::mem::size_of::(), 40); - assert_eq!(std::mem::offset_of!(Desc, parameter_count), 0); - assert_eq!(std::mem::offset_of!(Desc, parameters), 8); - assert_eq!(std::mem::offset_of!(Desc, sampler_count), 16); - assert_eq!(std::mem::offset_of!(Desc, samplers), 24); - assert_eq!(std::mem::offset_of!(Desc, flags), 32); - assert_eq!(std::mem::size_of::(), 48); - assert_eq!(std::mem::offset_of!(VersionedDesc, version), 0); - assert_eq!(std::mem::offset_of!(VersionedDesc, desc), 8); - } - - #[test] - fn console_flags_are_dropped_and_the_rest_kept() { - assert_eq!(CONSOLE_FLAGS, 0xff00_0000); - let desc = Desc { - parameter_count: 2, - parameters: BLOB.as_ptr().cast(), - sampler_count: 1, - samplers: BLOB.as_ptr().cast(), - flags: 0xffff_ffff, - }; - let plain = without_console_flags(desc); - assert_eq!(plain.flags, 0x00ff_ffff); - assert_eq!((plain.parameter_count, plain.sampler_count), (2, 1)); - assert!(std::ptr::eq(plain.parameters, desc.parameters)); - assert!(std::ptr::eq(plain.samplers, desc.samplers)); - - let low = Desc { - flags: 0x00ab_cdef, - ..desc - }; - assert_eq!(without_console_flags(low).flags, 0x00ab_cdef); - let none = Desc { flags: 0, ..desc }; - assert_eq!(without_console_flags(none).flags, 0); - } - - #[test] - fn serializers_reject_a_null_description() { - let mut blob = std::ptr::null_mut(); - let mut error = std::ptr::null_mut(); - assert_eq!( - serialize(std::ptr::null(), 1, &mut blob, &mut error), - E_INVALIDARG - ); - assert_eq!( - serialize_versioned(std::ptr::null(), &mut blob, &mut error), - E_INVALIDARG - ); - assert!(blob.is_null() && error.is_null()); - } - - /// A null `riid` used to be forwarded to the host, which dereferences it - /// (an access violation in `d3d12.dll`); an empty blob is malformed. - #[test] - fn deserializer_creation_rejects_missing_arguments() { - let iid = ROOT_SIGNATURE_IIDS[0]; - let mut out = std::ptr::null_mut(); - assert_eq!( - create_deserializer(std::ptr::null(), BLOB.len(), &iid, &mut out), - E_INVALIDARG - ); - assert_eq!( - create_deserializer(BLOB.as_ptr(), BLOB.len(), std::ptr::null(), &mut out), - E_INVALIDARG - ); - assert_eq!( - create_deserializer(BLOB.as_ptr(), 0, &iid, &mut out), - E_INVALIDARG - ); - assert_eq!( - create_deserializer(BLOB.as_ptr(), BLOB.len(), &iid, std::ptr::null_mut()), - E_INVALIDARG - ); - assert!(out.is_null()); - } - - #[test] - fn creating_a_root_signature_checks_its_arguments() { - let iid = ROOT_SIGNATURE_IIDS[0]; - let mut out = std::ptr::null(); - assert_eq!( - create( - std::ptr::null(), - 0, - std::ptr::null(), - BLOB.len(), - &iid, - &mut out - ), - E_INVALIDARG - ); - assert_eq!( - create(std::ptr::null(), 0, BLOB.as_ptr(), 0, &iid, &mut out), - E_INVALIDARG - ); - assert!(out.is_null()); - - // An unknown interface is dropped, and the answer is null. - assert_eq!( - create( - std::ptr::null(), - 0, - BLOB.as_ptr(), - BLOB.len(), - &OTHER_IID, - &mut out - ), - E_NOINTERFACE - ); - assert!(out.is_null()); - assert_eq!( - create( - std::ptr::null(), - 0, - BLOB.as_ptr(), - BLOB.len(), - std::ptr::null(), - &mut out - ), - E_NOINTERFACE - ); - assert!(out.is_null()); - - // Nowhere to write means the title only asked whether creation works. - assert_eq!( - create( - std::ptr::null(), - 0, - BLOB.as_ptr(), - BLOB.len(), - &iid, - std::ptr::null_mut() - ), - S_FALSE - ); - } - - #[test] - fn every_known_interface_creates_a_working_object() { - let root = created(&ROOT_SIGNATURE_IIDS[0]); - let query = slot:: HRESULT>(root, 0); - for iid in &ROOT_SIGNATURE_IIDS { - let mut out = std::ptr::null(); - assert_eq!(query(root, iid, &mut out), S_OK); - assert!(std::ptr::eq(out, root)); - assert_eq!(object::release(out), 1, "the original reference remains"); - } - let mut out = std::ptr::null(); - assert_eq!(query(root, &OTHER_IID, &mut out), E_NOINTERFACE); - assert!(out.is_null()); - assert_eq!(query(root, std::ptr::null(), &mut out), E_NOINTERFACE); - assert_eq!( - query(root, &ROOT_SIGNATURE_IIDS[0], std::ptr::null_mut()), - E_POINTER - ); - assert_eq!(object::release(root), 0); - } - - #[test] - fn the_table_has_the_object_and_device_child_slots() { - let root = created(&ROOT_SIGNATURE_IIDS[1]); - // SetPrivateDataInterface is the one object method left out. - assert_eq!( - slot:: HRESULT>(root, 0x28)(), - E_NOTIMPL - ); - assert_eq!( - slot:: HRESULT>(root, 0x30)( - root, - std::ptr::null() - ), - S_OK - ); - // GetDevice: an unknown interface is answered, not dereferenced. - let mut device = std::ptr::null(); - let get_device = - slot:: HRESULT>(root, 0x38); - assert_eq!( - get_device(root, std::ptr::null(), &mut device), - E_NOINTERFACE - ); - assert!(device.is_null()); - assert_eq!(object::release(root), 0); - } + use crate::object::{S_OK, slot}; /// One 32-bit constant at b0, serialized by the host, then created. #[cfg(windows)] @@ -539,48 +321,4 @@ mod tests { E_INVALIDARG ); } - - /// Truncated and nonsense blobs reach the host, which rejects them - /// without writing an object. - #[cfg(windows)] - #[test] - fn malformed_blobs_are_rejected_by_the_host() { - use windows::Win32::Graphics::Direct3D12::ID3D12RootSignatureDeserializer; - use windows::core::Interface; - let desc = VersionedDesc { - version: 1, - desc: Desc { - parameter_count: 0, - parameters: std::ptr::null(), - sampler_count: 0, - samplers: std::ptr::null(), - flags: 1, - }, - }; - let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut()); - assert_eq!(serialize_versioned(&desc, &mut blob, &mut error), S_OK); - let blob = blob.cast_const().cast::(); - let data = slot:: *const u8>(blob, 0x18)(blob); - let size = slot:: usize>(blob, 0x20)(blob); - let iid: Iid = ID3D12RootSignatureDeserializer::IID.to_u128().to_be_bytes(); - let iid = guid( - u32::from_be_bytes(iid[0..4].try_into().unwrap()), - u16::from_be_bytes(iid[4..6].try_into().unwrap()), - u16::from_be_bytes(iid[6..8].try_into().unwrap()), - iid[8..16].try_into().unwrap(), - ); - let mut out = std::ptr::null_mut(); - assert_eq!( - create_deserializer(data, size - 1, &iid, &mut out), - E_INVALIDARG - ); - assert!(out.is_null()); - let garbage = [0xffu8; 64]; - assert_eq!( - create_deserializer(garbage.as_ptr(), garbage.len(), &iid, &mut out), - E_INVALIDARG - ); - assert!(out.is_null()); - slot:: u32>(blob, 0x10)(blob); - } } diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 869d7d9..34ac4ac 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -3,8 +3,7 @@ //! that translated it (the BLAKE3 of our executable), so a rebuilt //! translator never serves an old translation. Entries go through //! `victory-pipeline`'s content-addressed cache, which writes them -//! atomically; an entry that does not read back is translated again, and a -//! cache that cannot be written is skipped (it never fails a translation). +//! atomically; an entry that does not read back is translated again. //! //! The entry is our own encoding of [`HostShader`]: a field added to it //! must be added to `encode` and `decode` too (entries of older builds @@ -12,10 +11,10 @@ use std::path::PathBuf; use std::sync::OnceLock; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use victory_pipeline::{Cache, Converter}; -use victory_shader::emit::{HostShader, MeshEmu, MeshMode, MeshOutput, StaticSampler, UserData}; +use victory_shader::emit::{HostShader, StaticSampler, UserData}; use victory_shader::resource::RootIndexedView; use victory_shader::{HwStage, RootType}; @@ -23,9 +22,6 @@ static CACHE: OnceLock = OnceLock::new(); static HITS: AtomicU64 = AtomicU64::new(0); static MISSES: AtomicU64 = AtomicU64::new(0); -/// The build fingerprint in front of every cache input, from [`build`]. -const BUILD_LEN: usize = 32; - /// Keeps translated shaders in `dir` from now on. pub fn use_shader_cache(dir: PathBuf) { match Cache::open(dir) { @@ -44,8 +40,8 @@ pub(crate) fn counts() -> (u64, u64) { /// What identifies this build: the BLAKE3 of our executable file and of /// the translation settings it runs with (the loop limit, which a /// diagnostics build can change at run time). -fn build() -> &'static [u8; BUILD_LEN] { - static BUILD: OnceLock<[u8; BUILD_LEN]> = OnceLock::new(); +fn build() -> &'static [u8; 32] { + static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); BUILD.get_or_init(|| { let exe = std::env::current_exe().and_then(std::fs::read); let limit = victory_shader::emit::loop_limit(); @@ -81,10 +77,8 @@ fn build() -> &'static [u8; BUILD_LEN] { } bytes.push(0); } - // Breadcrumbs change the code; off, the key is what it was. - if victory_shader::emit::breadcrumbs() { - bytes.extend_from_slice(b"breadcrumbs"); - } + // And which clean-up passes ran over the translated code. + bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes()); *blake3::hash(&bytes).as_bytes() } Err(e) => { @@ -101,82 +95,53 @@ fn build() -> &'static [u8; BUILD_LEN] { /// The translation of a console shader container, from the cache when /// there is one. -/// The translation of a console shader container in `mesh` mode. Native and -/// emulated mesh translations use separate converter ids: the same console -/// container has two independent cache entries. -pub(crate) fn host_shader(container: &[u8], mesh: MeshMode) -> Result { - let id = match mesh { - MeshMode::Native => "shader.dxil", - MeshMode::Emulate => "shader.dxil.mesh-emu", - }; - let translate = - |c: &[u8]| victory_shader::emit::translate_with(c, mesh).map_err(|e| e.to_string()); +pub(crate) fn host_shader(container: &[u8]) -> Result { + let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); match CACHE.get() { - Some(cache) => cached(cache, build(), id, container, translate), + Some(cache) => cached(cache, build(), container, translate), None => translate(container), } } /// The cache entry's converter: the build and the container in, the -/// encoded translation out. `translated` keeps what it produced, so a -/// store that cannot publish the entry costs no second translation. +/// encoded translation out. `ran` tells a miss from a hit. struct Translate { - id: &'static str, translate: F, - translated: OnceLock, + ran: AtomicBool, } impl Result + Send + Sync> Converter for Translate { fn id(&self) -> &'static str { - self.id + "shader.dxil" } fn version(&self) -> u32 { // The build fingerprint in the input does the versioning. 1 } fn convert(&self, input: &[u8]) -> anyhow::Result> { - let Some((_, container)) = input.split_at_checked(BUILD_LEN) else { - anyhow::bail!("shader cache input lacks the build fingerprint"); - }; - let shader = (self.translate)(container).map_err(anyhow::Error::msg)?; - let _ = self.translated.set(shader.clone()); + self.ran.store(true, Ordering::Relaxed); + let shader = (self.translate)(&input[32..]).map_err(anyhow::Error::msg)?; Ok(encode(&shader)) } } fn cached( cache: &Cache, - build: &[u8; BUILD_LEN], - id: &'static str, + build: &[u8; 32], container: &[u8], translate: impl Fn(&[u8]) -> Result + Send + Sync, ) -> Result { let input = [&build[..], container].concat(); let converter = Translate { - id, translate, - translated: OnceLock::new(), + ran: AtomicBool::new(false), }; for _ in 0..2 { - let path = match cache.get_or_convert(&converter, &input) { - Ok(path) => path, - // The cache never fails a translation: a store it cannot publish - // still holds the translation (a miss), and a translation that - // failed inside it fails here. - Err(e) => { - let message = format!("{e:#}"); - tracing::debug!(error = %message, "shader cache unusable"); - return match converter.translated.get() { - Some(shader) => { - MISSES.fetch_add(1, Ordering::Relaxed); - Ok(shader.clone()) - } - None => Err(message), - }; - } - }; + let path = cache + .get_or_convert(&converter, &input) + .map_err(|e| format!("{e:#}"))?; if let Some(shader) = std::fs::read(&path).ok().and_then(|b| decode(&b)) { - let (counter, what) = if converter.translated.get().is_some() { + let (counter, what) = if converter.ran.load(Ordering::Relaxed) { (&MISSES, "translated and cached") } else { (&HITS, "from the cache") @@ -189,15 +154,10 @@ fn cached( let _ = std::fs::remove_file(&path); } MISSES.fetch_add(1, Ordering::Relaxed); - // A translation that already happened (the store had no usable entry - // afterwards) is used as is. - if let Some(shader) = converter.translated.get() { - return Ok(shader.clone()); - } (converter.translate)(container) } -const MAGIC: &[u8; 4] = b"VSH3"; +const MAGIC: &[u8; 4] = b"VSH1"; const STAGES: [HwStage; 8] = [ HwStage::Ls, HwStage::Hs, @@ -209,11 +169,7 @@ const STAGES: [HwStage; 8] = [ HwStage::Cs, ]; -/// The tag of [`RootType::Other`]: a tag cannot hold every `u32`, so its -/// raw value follows it as its own word. -const OTHER_ROOT: u32 = 6; - -fn root_tag(r: RootType) -> u32 { +fn root_code(r: RootType) -> u32 { match r { RootType::Constants => 0, RootType::Descriptor => 1, @@ -221,12 +177,23 @@ fn root_tag(r: RootType) -> u32 { RootType::ImmediateSampler => 3, RootType::ResourceHeap => 4, RootType::SamplerHeap => 5, - RootType::Other(_) => OTHER_ROOT, + RootType::Other(x) => 6 + x, } } -/// Little-endian words and length-prefixed lists; a root type is its tag, -/// then the raw value for [`RootType::Other`]. +fn root_type(code: u32) -> RootType { + match code { + 0 => RootType::Constants, + 1 => RootType::Descriptor, + 2 => RootType::Table, + 3 => RootType::ImmediateSampler, + 4 => RootType::ResourceHeap, + 5 => RootType::SamplerHeap, + x => RootType::Other(x - 6), + } +} + +/// Little-endian words and length-prefixed lists. fn encode(s: &HostShader) -> Vec { let mut out = MAGIC.to_vec(); let word = |out: &mut Vec, v: u32| out.extend(v.to_le_bytes()); @@ -236,13 +203,9 @@ fn encode(s: &HostShader) -> Vec { out.extend(&s.dxil); word(&mut out, s.user_data.len() as u32); for u in &s.user_data { - for v in [u.index, u32::from(u.slot), root_tag(u.root)] { + for v in [u.index, u32::from(u.slot), root_code(u.root), u.dword] { word(&mut out, v); } - if let RootType::Other(raw) = u.root { - word(&mut out, raw); - } - word(&mut out, u.dword); } word(&mut out, s.samplers.len() as u32); for sampler in &s.samplers { @@ -273,8 +236,6 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, slots.len() as u32); out.extend(slots); } - word(&mut out, u32::from(s.address_map)); - word(&mut out, u32::from(s.descriptor_words)); word(&mut out, s.root_indexed_views.len() as u32); for view in &s.root_indexed_views { for value in [ @@ -287,44 +248,6 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, value); } } - let encode_outputs = |out: &mut Vec, items: &[MeshOutput]| { - word(out, items.len() as u32); - for o in items { - let name = o.name.as_bytes(); - word(out, name.len() as u32); - out.extend(name); - for v in [ - o.index, - u32::from(o.kind), - u32::from(o.comp), - u32::from(o.interp), - o.row.unwrap_or(u32::MAX), - u32::from(o.col), - u32::from(o.cols), - o.dword_offset, - ] { - word(out, v); - } - } - }; - match &s.mesh_emu { - None => word(&mut out, 0), - Some(m) => { - word(&mut out, 1); - for v in [ - m.threads, - m.max_vertices, - m.max_primitives, - m.vertex_dwords, - m.prim_dwords, - u32::from(m.reads_group_id), - ] { - word(&mut out, v); - } - encode_outputs(&mut out, &m.vertex_outputs); - encode_outputs(&mut out, &m.prim_outputs); - } - } out } @@ -343,36 +266,6 @@ fn decode(bytes: &[u8]) -> Option { let n = self.word()? as usize; Some(self.take(n)?.to_vec()) } - fn outputs(&mut self) -> Option> { - let n = self.word()? as usize; - let mut out = Vec::with_capacity(n.min(256)); - for _ in 0..n { - let name = String::from_utf8(self.list()?).ok()?; - let index = self.word()?; - let kind = u8::try_from(self.word()?).ok()?; - let comp = u8::try_from(self.word()?).ok()?; - let interp = u8::try_from(self.word()?).ok()?; - let row = match self.word()? { - u32::MAX => None, - r => Some(r), - }; - let col = u8::try_from(self.word()?).ok()?; - let cols = u8::try_from(self.word()?).ok()?; - let dword_offset = self.word()?; - out.push(MeshOutput { - name, - index, - kind, - comp, - interp, - row, - col, - cols, - dword_offset, - }); - } - Some(out) - } } let mut r = Reader(bytes); if r.take(4)? != MAGIC { @@ -383,22 +276,10 @@ fn decode(bytes: &[u8]) -> Option { let n = r.word()? as usize; let mut user_data = Vec::with_capacity(n.min(256)); for _ in 0..n { - let index = r.word()?; - let slot = u8::try_from(r.word()?).ok()?; - let root = match r.word()? { - 0 => RootType::Constants, - 1 => RootType::Descriptor, - 2 => RootType::Table, - 3 => RootType::ImmediateSampler, - 4 => RootType::ResourceHeap, - 5 => RootType::SamplerHeap, - OTHER_ROOT => RootType::Other(r.word()?), - _ => return None, - }; user_data.push(UserData { - index, - slot, - root, + index: r.word()?, + slot: u8::try_from(r.word()?).ok()?, + root: root_type(r.word()?), dword: r.word()?, }); } @@ -424,13 +305,6 @@ fn decode(bytes: &[u8]) -> Option { let root_cbvs = r.list()?; let root_srvs = r.list()?; let root_uavs = r.list()?; - let flag = |w: u32| match w { - 0 => Some(false), - 1 => Some(true), - _ => None, - }; - let address_map = flag(r.word()?)?; - let descriptor_words = flag(r.word()?)?; let n = r.word()? as usize; let mut root_indexed_views = Vec::with_capacity(n.min(256)); for _ in 0..n { @@ -442,20 +316,6 @@ fn decode(bytes: &[u8]) -> Option { shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?, }); } - let mesh_emu = match r.word()? { - 0 => None, - 1 => Some(MeshEmu { - threads: r.word()?, - max_vertices: r.word()?, - max_primitives: r.word()?, - vertex_dwords: r.word()?, - prim_dwords: r.word()?, - reads_group_id: flag(r.word()?)?, - vertex_outputs: r.outputs()?, - prim_outputs: r.outputs()?, - }), - _ => return None, - }; r.0.is_empty().then_some(HostShader { stage, dxil, @@ -464,18 +324,14 @@ fn decode(bytes: &[u8]) -> Option { static_samplers, root_cbvs, root_srvs, - address_map, - descriptor_words, root_uavs, root_indexed_views, - mesh_emu, }) } #[cfg(test)] mod tests { use super::*; - use victory_pipeline::CacheKey; fn shader() -> HostShader { HostShader { @@ -496,8 +352,6 @@ mod tests { ])], root_cbvs: vec![2], root_srvs: vec![0, 3], - address_map: true, - descriptor_words: true, root_uavs: vec![1], root_indexed_views: vec![RootIndexedView { table_slot: 1, @@ -506,59 +360,9 @@ mod tests { byte_offset: 32, shift: 5, }], - mesh_emu: None, } } - fn mesh_emu_shader() -> HostShader { - let mut s = shader(); - s.stage = HwStage::Ms; - s.mesh_emu = Some(MeshEmu { - threads: 64, - max_vertices: 32, - max_primitives: 16, - vertex_dwords: 8, - prim_dwords: 4, - reads_group_id: true, - vertex_outputs: vec![ - MeshOutput { - name: "SV_Position".into(), - index: 0, - kind: 3, - comp: 9, - interp: 4, - row: None, - col: 0, - cols: 4, - dword_offset: 0, - }, - MeshOutput { - name: "COLOR".into(), - index: 0, - kind: 0, - comp: 9, - interp: 2, - row: Some(0), - col: 0, - cols: 4, - dword_offset: 4, - }, - ], - prim_outputs: vec![MeshOutput { - name: "PRIMID".into(), - index: 0, - kind: 0, - comp: 5, - interp: 1, - row: Some(1), - col: 0, - cols: 1, - dword_offset: 0, - }], - }); - s - } - #[test] fn translations_come_back_from_the_cache() { let dir = tempfile::tempdir().unwrap(); @@ -570,59 +374,26 @@ mod tests { runs.fetch_add(1, Ordering::Relaxed); Ok(shader()) }; - assert_eq!( - cached(&cache, &build, "shader.dxil", container, translate), - Ok(shader()) - ); - assert_eq!( - cached(&cache, &build, "shader.dxil", container, translate), - Ok(shader()) - ); + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk"); - // Another converter id caches separately. - let emu_runs = AtomicU64::new(0); - let emu_translate = |_: &[u8]| { - emu_runs.fetch_add(1, Ordering::Relaxed); - Ok(mesh_emu_shader()) - }; - assert_eq!( - cached( - &cache, - &build, - "shader.dxil.mesh-emu", - container, - emu_translate, - ), - Ok(mesh_emu_shader()) - ); - assert_eq!(emu_runs.load(Ordering::Relaxed), 1); - // Another build translates again. - assert_eq!( - cached(&cache, &[8; 32], "shader.dxil", container, translate), - Ok(shader()) - ); + assert_eq!(cached(&cache, &[8; 32], container, translate), Ok(shader())); assert_eq!(runs.load(Ordering::Relaxed), 2); // A damaged entry is a miss, translated and stored again. for e in walk(dir.path()) { - std::fs::write(e, b"VSH3 broken").unwrap(); + std::fs::write(e, b"VSH1 broken").unwrap(); } - assert_eq!( - cached(&cache, &build, "shader.dxil", container, translate), - Ok(shader()) - ); + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); assert_eq!(runs.load(Ordering::Relaxed), 3); - assert_eq!( - cached(&cache, &build, "shader.dxil", container, translate), - Ok(shader()) - ); + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); assert_eq!(runs.load(Ordering::Relaxed), 3); // Failures are not stored. let fail = |_: &[u8]| Err::("unsupported".to_owned()); - assert!(cached(&cache, &build, "shader.dxil", b"other", fail).is_err()); + assert!(cached(&cache, &build, b"other", fail).is_err()); } fn walk(dir: &std::path::Path) -> Vec { @@ -637,272 +408,12 @@ mod tests { files } - /// A shader with every field at an unusual value. - fn rich_shader() -> HostShader { - HostShader { - stage: HwStage::Gs, - dxil: (0u8..=255).collect(), - user_data: vec![ - UserData { - index: 0, - slot: 0, - root: RootType::Constants, - dword: 1, - }, - UserData { - index: 7, - slot: 255, - root: RootType::Other(0xdead_beef), - dword: u32::MAX, - }, - UserData { - index: u32::MAX, - slot: 2, - root: RootType::SamplerHeap, - dword: 3, - }, - ], - samplers: vec![[1, 2, 3, 4], [0, 0, 0, 0]], - static_samplers: vec![ - StaticSampler::from_words([0x400, 0xc0_0000, 0x18f0_0000, 0]), - StaticSampler::from_words([0, 0, 0, 0]), - ], - root_cbvs: vec![0, 1, 255], - root_srvs: vec![2], - address_map: true, - descriptor_words: true, - root_uavs: Vec::new(), - root_indexed_views: Vec::new(), - mesh_emu: None, - } - } - #[test] fn entries_round_trip_and_reject_damage() { - for shader in [shader(), mesh_emu_shader()] { - let bytes = encode(&shader); - assert_eq!(decode(&bytes), Some(shader)); - assert_eq!(decode(&bytes[..bytes.len() - 1]), None); - assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None); - } - assert_eq!(decode(b"VSH2"), None); - } - - #[test] - fn the_whole_shader_survives_the_round_trip() { - assert_eq!(decode(&encode(&rich_shader())), Some(rich_shader())); - } - - #[test] - fn every_stage_round_trips() { - let stages = [ - HwStage::Ls, - HwStage::Hs, - HwStage::Es, - HwStage::Gs, - HwStage::Vs, - HwStage::Ps, - HwStage::Ms, - HwStage::Cs, - ]; - for stage in stages { - let mut s = shader(); - s.stage = stage; - assert_eq!(decode(&encode(&s)), Some(s.clone()), "{stage:?}"); - } - } - - #[test] - fn every_root_type_round_trips() { - let roots = [ - RootType::Constants, - RootType::Descriptor, - RootType::Table, - RootType::ImmediateSampler, - RootType::ResourceHeap, - RootType::SamplerHeap, - RootType::Other(0), - RootType::Other(1), - RootType::Other(6), - RootType::Other(u32::MAX), - ]; - for root in roots { - let mut s = shader(); - s.user_data[0].root = root; - assert_eq!(decode(&encode(&s)), Some(s.clone()), "{root:?}"); - } - } - - #[test] - fn every_truncation_is_not_a_shader() { - let bytes = encode(&rich_shader()); - for n in 0..bytes.len() { - assert_eq!(decode(&bytes[..n]), None, "{n} of {} bytes", bytes.len()); - } - assert_eq!(decode(&bytes), Some(rich_shader())); - } - - #[test] - fn impossible_lengths_are_not_shaders() { - let s = rich_shader(); - let bytes = encode(&s); - - // The DXIL length (after the magic and the stage). - let mut b = bytes.clone(); - b[8..12].copy_from_slice(&u32::MAX.to_le_bytes()); - assert_eq!(decode(&b), None, "an oversized DXIL"); - - // The user-data count (after the DXIL). - let at = 12 + s.dxil.len(); - let mut b = bytes.clone(); - b[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); - assert_eq!(decode(&b), None, "too many user-data entries"); - - // The root-SRV list's length: the bytes it promises are not there. - let mut at = 12 + s.dxil.len() + 4; - for u in &s.user_data { - at += 16 + usize::from(matches!(u.root, RootType::Other(_))) * 4; - } - at += 4 + s.samplers.len() * 16; - at += 4 + s.static_samplers.len() * 40; - at += 4 + s.root_cbvs.len(); - let mut b = bytes.clone(); - b[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); - assert_eq!(decode(&b), None, "a root SRV list that is not there"); - } - - #[test] - fn unknown_root_tags_are_not_shaders() { - let s = shader(); - let bytes = encode(&s); - // The first user-data entry: count, index, slot, then the root tag. - let at = 12 + s.dxil.len() + 4 + 4 + 4; - for tag in [7u32, 1000, u32::MAX] { - let mut b = bytes.clone(); - b[at..at + 4].copy_from_slice(&tag.to_le_bytes()); - assert_eq!(decode(&b), None, "{tag}"); - } - } - - #[test] - fn damaged_entries_never_panic() { - let bytes = encode(&rich_shader()); - for at in 0..bytes.len() { - for xor in [0x01u8, 0x80, 0xff] { - let mut b = bytes.clone(); - b[at] ^= xor; - let _ = decode(&b); - } - } - // Entries that are not one of ours: arbitrary bytes behind the magic. - let mut state = 0x9e37_79b9_7f4a_7c15u64; - for len in 0..96 { - let mut b = b"VSH1".to_vec(); - for _ in 0..len { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - b.push(state as u8); - } - let _ = decode(&b); - } - } - - #[test] - fn each_container_and_build_keeps_its_own_entry() { - let dir = tempfile::tempdir().unwrap(); - let cache = Cache::open(dir.path()).unwrap(); - let runs = AtomicU64::new(0); - let translate = |c: &[u8]| { - runs.fetch_add(1, Ordering::Relaxed); - let mut s = shader(); - s.dxil = c.to_vec(); - Ok(s) - }; - let of = |c: &[u8]| { - let mut s = shader(); - s.dxil = c.to_vec(); - s - }; - let (a, b) = (b"first container".as_slice(), b"second container"); - assert_eq!( - cached(&cache, &[7; 32], "shader.dxil", a, translate), - Ok(of(a)) - ); - assert_eq!( - cached(&cache, &[7; 32], "shader.dxil", b, translate), - Ok(of(b)) - ); - assert_eq!(runs.load(Ordering::Relaxed), 2); - assert_eq!(walk(dir.path()).len(), 2, "one entry per container"); - - assert_eq!( - cached(&cache, &[7; 32], "shader.dxil", a, translate), - Ok(of(a)) - ); - assert_eq!( - cached(&cache, &[7; 32], "shader.dxil", b, translate), - Ok(of(b)) - ); - assert_eq!(runs.load(Ordering::Relaxed), 2, "both came from the cache"); - - // Another build's translation is a separate entry too. - assert_eq!( - cached(&cache, &[8; 32], "shader.dxil", b, translate), - Ok(of(b)) - ); - assert_eq!(runs.load(Ordering::Relaxed), 3); - assert_eq!(walk(dir.path()).len(), 3); - } - - #[test] - fn a_cache_that_cannot_be_written_still_translates() { - // A directory where the entry goes makes the atomic rename fail. - let dir = tempfile::tempdir().unwrap(); - let cache = Cache::open(dir.path()).unwrap(); - let build = [7; 32]; - let container = b"a console container".as_slice(); - let translate = |_: &[u8]| -> Result { Ok(shader()) }; - let converter = Translate { - id: "shader.dxil", - translate, - translated: OnceLock::new(), - }; - let input = [&build[..], container].concat(); - let path = cache.path_for(&CacheKey::new(&converter, &input)); - std::fs::create_dir_all(&path).unwrap(); - - let runs = AtomicU64::new(0); - let translate = |_: &[u8]| { - runs.fetch_add(1, Ordering::Relaxed); - Ok(shader()) - }; - assert_eq!( - cached(&cache, &build, "shader.dxil", container, translate), - Ok(shader()) - ); - assert_eq!(runs.load(Ordering::Relaxed), 1, "no second translation"); - assert!(path.is_dir(), "the entry path is still unusable"); - } - - #[test] - fn the_converter_needs_the_build_fingerprint() { - let converter = Translate { - id: "shader.dxil", - translate: |c: &[u8]| -> Result { - let mut s = shader(); - s.dxil = c.to_vec(); - Ok(s) - }, - translated: OnceLock::new(), - }; - assert!(converter.convert(b"short").is_err()); - let input = [&[0u8; 32][..], b"container"].concat(); - let mut expected = shader(); - expected.dxil = b"container".to_vec(); - assert_eq!( - converter.convert(&input).ok().and_then(|b| decode(&b)), - Some(expected) - ); + let bytes = encode(&shader()); + assert_eq!(decode(&bytes), Some(shader())); + assert_eq!(decode(&bytes[..bytes.len() - 1]), None); + assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None); + assert_eq!(decode(b"VSH0"), None); } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 94c400b..133e871 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -16,7 +16,7 @@ //! indexed heaps keep what their first use copied. use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU8, AtomicU32, Ordering}; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use windows::Win32::Graphics::Direct3D12::ID3D12Resource; @@ -27,8 +27,6 @@ use crate::watch::PAGE; /// A title buffer's host copy. pub(crate) struct Shadow { pub(crate) buffer: ID3D12Resource, - /// The D3D12 state of this host copy between submissions (buffers decay to COMMON). - pub(crate) state: AtomicU32, data: *mut u8, gpu: u64, /// Where the title buffer starts and how long it is. @@ -42,21 +40,795 @@ pub(crate) struct Shadow { /// Ranges shaders of a submission not yet copied back may be writing: /// title memory there is older than the copy. pending: Mutex>, - /// The copy's bytes before the submission ran, from an offset on, - /// covering the ranges its shaders write: what the GPU wrote differs. - before: Mutex)>>, + /// With [`relay`]: how many submissions not yet copied back declared + /// each range of `pending` ([`Flights`]). Locked inside `pending`'s + /// lock. + flights: Mutex, + /// The copy's bytes before the submission ran, for the ranges its + /// shaders write (`pending`), each at its offset in the copy: what the + /// GPU wrote differs. Room for the whole copy; only those ranges' bytes + /// are set (and read). + before: Mutex>>, + /// With snapshots kept ([`keeps`]): which 64 KiB pieces of the snapshot + /// hold the copy's bytes as they are now, and whether the snapshot is + /// counted in [`KEPT_BYTES`]. + kept: Mutex<(Vec, bool)>, + /// When the copy was last asked for (`crate::host::moment`): a window + /// outside buffers nothing asked for in a while, and nothing holds, is + /// let go ([`let_go_idle`]). + used: AtomicU64, + /// The lowest and highest title address asked for in the copy (a + /// window is 4 MiB whatever was asked: measured for the memory line). + asked: [AtomicU64; 2], + /// Asks for the copy that gave no length (root views: they read from + /// their address to the copy's end, whatever lies there). + unsized_asks: AtomicU64, + /// A number no other copy has had. Its address is no name for a copy: + /// one let go and another made may share it. + id: u64, + /// With [`cards`], for a big title buffer: `buffer` is in the card's + /// own memory, and this is the rest of the copy. + card: Option, + /// A window of title memory outside buffers, not a title buffer's copy. + window: bool, + /// With `crate::inplace`: not a copy at all. `buffer` is placed in a + /// heap opened on the title memory itself, so shaders read and write + /// the title's own bytes and nothing is copied either way. The heap, + /// and the bytes from the buffer's first byte to `start` (the heap + /// begins on a 64 KiB line; a title buffer need not). + place: Option<(windows::Win32::Graphics::Direct3D12::ID3D12Heap, u64)>, +} + +/// What a copy in the card's memory ([`cards`]) has beside the buffer +/// shaders see. +struct Card { + /// The CPU's side, in the PC's memory: what `data` maps. Title memory + /// is copied into it as into any copy, and what changed in it goes to + /// the card's side before the next submission. + staging: ID3D12Resource, + /// The card side's bytes as they were when the submission's shaders + /// started, in the card's memory too: made when shader writes are + /// first declared for the copy, and compared with the card's side, on + /// the card, after each submission that declares some. + before: Mutex>, + /// Offsets of the copy whose bytes changed on the CPU's side and have + /// not gone to the card's side yet. + dirty: Mutex>, + /// With [`relay`]: the offsets that went from `dirty` to the card's + /// side, each with the number of the send that took it + /// ([`card_dirty`]), kept until a fetch sent after it has been merged. + /// Locked inside `dirty`'s lock. + sent: Mutex>, + /// The buffers' bytes (the title buffer's, rounded up to 64 KiB). + size: u64, +} + +/// Whether the host copies of big title buffers are in the card's own +/// memory (on by default since run 75 showed it holds: the BVH skinning +/// list went from 50.5 to 4.5 ms on the card; `VICTORY_CARD_BUFFERS=0` +/// keeps every copy in the PC's memory, as before. Read when a copy is +/// made, so it takes a fresh start). +/// +/// Every host copy was a buffer in the PC's memory that the card reads +/// and writes over the bus, so that our code can fill it and compare it. +/// The title's shaders read almost all their buffer data from a few big +/// title buffers (in the gameplay frame of run 69, 190-330 MB of distinct +/// ranges of the 174 MB heap per list against 0-13 MB elsewhere), and a +/// skinning dispatch of ONE group of 32 threads took 1.8 ms on the card +/// (run 70): the time of some 170 loads one after the other, not of the +/// arithmetic. +/// +/// With the switch, a title buffer of [`card_limits`]' size or more has two +/// sides. Shaders see `Shadow::buffer`, in the card's memory. The CPU's +/// side (`Card::staging`, what `Shadow::data` maps) takes title memory as +/// before, and the ranges that changed in it are copied to the card's side +/// before each submission (`Host::card_before`). What shaders wrote is +/// found on the card: after the submission's lists a compute pass of ours +/// compares each declared range, by 64 KiB piece, with the card side's +/// bytes from before (`Card::before`), and only the pieces that differ are +/// fetched and merged into title memory, byte by byte as +/// [`Shadow::copy_back`] does (`Host::card_back`, [`Shadow::card_merge`]). +/// No snapshot is taken and nothing is compared on the CPU for such a copy. +/// +/// What it assumes is what [`keeps`] assumes: shaders write a copy only in +/// ranges declared as written. A write outside them is seen by later +/// shaders, as before, and goes back to the title the next time a declared +/// range holds its piece (before: never). +pub(crate) fn cards() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_BUFFERS").is_none_or(|v| v != "0")) +} + +/// The smallest title buffer whose copy goes to the card's memory, and the +/// most bytes of such copies (their "before" twins not counted: a copy +/// shaders write takes its size twice), both in bytes: +/// `VICTORY_CARD_BUFFERS_MIN_MB` (16) and `VICTORY_CARD_BUFFERS_MB` (512). +/// Run 69's gameplay has ten title buffers of 16 MiB or more, 494 MB, and +/// 1,650 MB of the card's budget free. +fn card_limits() -> (u64, u64) { + static LIMITS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); + *LIMITS.get_or_init(|| { + let mb = |name: &str, default: u64| { + std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(default) << 20 + }; + // From 1 MiB up and 1,024 MB in all by default (it was 16 and 512): + // the shader writes of the smaller buffers are then found by the + // card's hashes too, and with that the first room's walls were + // drawn in every run. + (mb("VICTORY_CARD_BUFFERS_MIN_MB", 1).max(1 << 20), mb("VICTORY_CARD_BUFFERS_MB", 1024)) + }) +} + +/// Bytes alive of copies' card sides, and of their "before" twins. +static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// The copies in the card's memory. +static CARDED: Mutex>> = Mutex::new(Vec::new()); + +/// Since the last frame line: bytes copied to card sides and the ranges +/// they were; pieces compared on the card, pieces fetched and their +/// bytes; the waits for the card the fetches added and their microseconds. +pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + +/// [`CARD_STATS`], taken; then the copies in the card's memory, their +/// bytes and their "before" twins' bytes. +pub(crate) fn card_stats() -> [u64; 10] { + let mut out = [0u64; 10]; + for (i, stat) in CARD_STATS.iter().enumerate() { + out[i] = stat.swap(0, Ordering::Relaxed); + } + out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64; + out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed); + out[9] = CARD_BYTES[1].load(Ordering::Relaxed); + out +} + +/// The bytes of the hashes kept on the card for a copy of `size` bytes: 16 +/// for each 64 KiB piece (a copy that does not start on a piece boundary +/// has one piece more). +pub(crate) fn card_hash_bytes(size: u64) -> u64 { + (size / PIECE as u64 + 2) * 16 +} + +/// A buffer of `size` bytes in the card's memory for a title buffer's +/// copy, if the copy is to be there: [`cards`] is on, the size is within +/// [`card_limits`] and below 1 GiB (the compare counts in 32 bits), and the +/// host has what it takes (`Host::card_ready`). +fn card_for(size: u64) -> Option { + if !cards() { + return None; + } + let (least, most) = card_limits(); + if size < least || size >= 1 << 30 { + return None; + } + let host = host()?; + if !host.card_ready() { + return None; + } + // Only while the card has room: with this copy on it, a fifth of the + // budget the system gives us must still be free. Copies are made when + // the world loads, before the textures fill the card; the texture + // queue's own rule (`resource::room`: nine tenths of the budget) counts + // them, so the card's use stays where it was and the textures' share + // shrinks by the copies' bytes, at most `card_limits`' second number. + if let Some([budget, used, ..]) = host.video_memory() + && used + size > budget / 10 * 8 + { + return None; + } + if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + size > most { + CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); + return None; + } + let buffer = host.uav_buffer(size); + if buffer.is_none() { + CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); + } + buffer +} + +/// The most bytes of windows outside buffers whose copies go to the card's +/// memory (`VICTORY_CARD_WINDOWS_MB`; 0, the default, none). +/// +/// Windows are two thirds of the PC memory the card shares (run 104: 861 +/// windows, 3,552 MB of 5,400), and every draw that takes vertices, indices +/// or constants from the title's own allocator reads them over the bus. +/// Shaders write none of them (run 91: "0.0 MB compared in 0 ranges of +/// windows"), so a window on the card needs only what a card copy has +/// already: the CPU's side takes title memory as before, and what changed +/// in it goes up before each submission. No hashes, no compare, no fetch, +/// unless a shader does declare a write to it one day. +/// +/// A window goes to the card while there is room under this number and +/// while a fifth of the card's budget is free, as title buffers do +/// (`card_for`): textures keep their room, and once they have filled the +/// card later windows stay where they are. The CPU's side stays in the PC's +/// memory, so the memory shared with the card does not shrink by this +/// alone; what moves is what shaders read. +fn window_card_most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_CARD_WINDOWS_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) << 20 + }) +} + +/// Bytes alive of windows' card sides ([`window_card_most`]). +static WINDOW_CARD_BYTES: AtomicU64 = AtomicU64::new(0); + +/// A buffer in the card's memory for a window of `size` bytes, if it is to +/// be there ([`window_card_most`]). +fn window_card_for(size: u64) -> Option { + let most = window_card_most(); + if most == 0 || !cards() { + return None; + } + let host = host()?; + if !host.card_ready() { + return None; + } + if let Some([budget, used, ..]) = host.video_memory() + && used + size > budget / 10 * 8 + { + return None; + } + if WINDOW_CARD_BYTES.fetch_add(size, Ordering::Relaxed) + size > most { + WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + return None; + } + let buffer = host.uav_buffer(size); + if buffer.is_none() { + WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + } + buffer +} + +/// The copies in the card's memory whose CPU side changed since they were +/// last asked: each with the changed offsets, in order and joined where +/// they touch. The ranges are taken: the caller copies them to the card's +/// side (`Host::card_before`). +/// +/// With [`relay`], `sent_as` is the number of the send that takes them +/// (`crate::host`'s order of the queue): each range is noted with it, in +/// the same lock that took it, so that a merge of pieces fetched before +/// that send knows the card did not hold these bytes yet +/// ([`Shadow::card_merge_relay`]). Notes of sends that every fetch still to +/// be merged came after are dropped. +pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc, Vec<(usize, usize)>)> { + let mut out = Vec::new(); + let mut carded = CARDED.lock().unwrap_or_else(|e| e.into_inner()); + let fetched = RELAY_FETCHED.load(Ordering::Acquire); + carded.retain(|weak| { + let Some(shadow) = weak.upgrade() else { + return false; + }; + let ranges = shadow + .card + .as_ref() + .map(|c| { + let mut dirty = c.dirty.lock().unwrap_or_else(|e| e.into_inner()); + let ranges = std::mem::take(&mut *dirty); + if relay() { + let mut sent = c.sent.lock().unwrap_or_else(|e| e.into_inner()); + sent.retain(|s| s.2 > fetched); + sent.extend(ranges.iter().map(|&(a, b)| (a, b, sent_as))); + } + ranges + }) + .unwrap_or_default(); + if !ranges.is_empty() { + out.push((shadow, joined(ranges))); + } + true + }); + out +} + +/// Ranges in order, those that overlap or touch as one. +fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + ranges.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for (from, to) in ranges { + match out.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => out.push((from, to)), + } + } + out +} + +/// Runs of pieces to hash again (`Host::card_before`), those that overlap +/// or touch as one, in order: every piece of `runs` is in the result once +/// and no other piece is. Ranges sent up lie close together (514 a frame +/// for 87 MB in run 102), and each had a pass of its own over its pieces, +/// so a piece that held several ranges was hashed once for each. +pub(crate) fn joined_piece_runs(mut runs: Vec) -> Vec { + runs.sort_unstable_by_key(|r| r.first); + let mut out: Vec = Vec::with_capacity(runs.len()); + for run in runs { + match out.last_mut() { + Some(last) if run.first <= last.first + last.pieces => { + last.pieces = last.pieces.max(run.first + run.pieces - last.first); + last.to = last.to.max(run.to); + } + _ => out.push(run), + } + } + out +} + +/// A declared range of a copy in the card's memory, as the compare on the +/// card takes it: its offsets in the copy, its first 64 KiB piece (pieces +/// are cut at multiples of 64 KiB of title memory; piece 0 holds offset +/// 0), how many pieces hold it, and where the copy starts in piece 0. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct CardSpan { + pub(crate) from: u32, + pub(crate) to: u32, + pub(crate) first: u32, + pub(crate) pieces: u32, + pub(crate) skew: u32, +} + +/// [`CardSpan`] for offsets `[from, to)` (`from < to`) of a copy of title +/// memory from `start` on. +fn card_span_of(start: usize, from: usize, to: usize) -> CardSpan { + let pieces = pieces_of(start, from, to); + CardSpan { + from: from as u32, + to: to as u32, + first: pieces.start as u32, + pieces: pieces.len() as u32, + skew: (start % PIECE) as u32, + } +} + +/// The offsets of piece `i` of `span` that lie in the span, for a copy of +/// `len` bytes of title memory from `start` on: what is fetched and merged +/// of a piece the compare found differing. +fn card_piece_of(start: usize, len: usize, span: &CardSpan, i: u32) -> (usize, usize) { + let (lo, hi) = piece_at(start, len, (span.first + i) as usize); + (lo.max(span.from as usize), hi.min(span.to as usize)) +} + +#[cfg(test)] +mod card_tests { + use super::{CardSpan, PIECE, card_piece_of, card_span_of, joined, joined_piece_runs}; + + /// Joined runs hold every piece of the runs given, once, and no other. + #[test] + fn piece_runs_join_without_losing_or_adding_pieces() { + let run = |first: u32, pieces: u32| CardSpan { + from: first * 65536, + to: (first + pieces) * 65536, + first, + pieces, + skew: 7, + }; + let runs = vec![run(40, 1), run(3, 2), run(4, 1), run(5, 3), run(40, 1), run(9, 1), run(41, 2), run(100, 1)]; + let mut wanted: Vec = runs.iter().flat_map(|r| r.first..r.first + r.pieces).collect(); + wanted.sort_unstable(); + wanted.dedup(); + let joined = joined_piece_runs(runs); + let got: Vec = joined.iter().flat_map(|r| r.first..r.first + r.pieces).collect(); + assert_eq!(got, wanted); + assert_eq!(joined.iter().map(|r| (r.first, r.pieces)).collect::>(), [(3, 5), (9, 1), (40, 3), (100, 1)]); + assert!(joined.iter().all(|r| r.skew == 7)); + assert!(joined_piece_runs(Vec::new()).is_empty()); + } + + /// The offsets the compare's shader takes for a piece (`CARD_COMPARE` + /// in host.rs), before it widens them to 16 bytes. + fn shader_piece(span: &CardSpan, i: u32) -> (u32, u32) { + let piece = span.first + i; + let lo = piece * 65536; + let lo = if lo > span.skew { lo - span.skew } else { 0 }; + let hi = (piece + 1) * 65536 - span.skew; + (lo.max(span.from), hi.min(span.to)) + } + + /// The pieces of a span cover it without gaps, and the shader's + /// arithmetic names the same bytes as ours. + #[test] + fn the_shader_and_the_merge_cut_the_same_pieces() { + for start in [0usize, 4096, PIECE - 16, PIECE, 3 * PIECE + 0x1f00, 0xd_b790_df00] { + let len = 5 * PIECE + 4096; + for (from, to) in [(0, len), (0, 1), (16, PIECE), (PIECE - 4, PIECE + 4), (2 * PIECE, len), (12345, 4 * PIECE + 7)] { + let span = card_span_of(start, from, to); + let mut at = from; + for i in 0..span.pieces { + let (lo, hi) = card_piece_of(start, len, &span, i); + assert_eq!(lo, at, "{start:#x} {from} {to} piece {i}"); + assert!(hi > lo && hi - lo <= PIECE); + assert_eq!(shader_piece(&span, i), (lo as u32, hi as u32), "{start:#x} {from} {to} piece {i}"); + at = hi; + } + assert_eq!(at, to, "{start:#x} {from} {to}"); + } + } + } + + /// Changed ranges are joined where they overlap or touch, and only there. + #[test] + fn ranges_join_where_they_touch() { + assert_eq!(joined(vec![(8, 12), (0, 4), (4, 6), (10, 20), (30, 31)]), [(0, 6), (8, 20), (30, 31)]); + assert!(joined(Vec::new()).is_empty()); + } +} + +/// Whether the copy-back of what shaders wrote runs on a thread of its own, +/// beside the submitting thread and outside the submission lock +/// (`VICTORY_RELAY=1` or `2`; off by default; not with kept snapshots, +/// [`keeps`]). `crate::host::relay` says what it does; here it changes +/// what a copy keeps: +/// +/// - the ranges shaders may be writing are counted per submission +/// ([`Flights`]): a range two flights declared stays closed to refreshes +/// until both have been copied back; +/// - the merge of what the card wrote never stores into memory the card +/// may be writing ([`merge_piece`]): what it learns goes into title +/// memory and into the copy's reference (the snapshot, or the CPU's side +/// of a copy in the card's memory), under that reference's lock; +/// - what goes up to a copy in the card's memory is numbered +/// ([`card_dirty`]), so that a merge can tell the title's bytes the card +/// had not received from bytes the card wrote. +pub(crate) fn relay() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + // On by default (stage 2, `crate::host::relay_exact`); `VICTORY_RELAY=0` + // turns it off, `=1` asks for the first stage. + // The crate's own tests run without it unless they ask: several of + // them look at title memory right after a submission, which the + // relay's landing thread may still be writing. + *ON.get_or_init(|| std::env::var("VICTORY_RELAY").map_or(!cfg!(test), |v| v == "1" || v == "2") && !keeps()) +} + +/// The submission being prepared (its number among those started): what +/// [`Shadow::writing`] counts a declared range for ([`Flights`]). +static PREPARED: AtomicU64 = AtomicU64::new(0); + +/// A submission's preparing begins (`crate::host`, under the submission +/// lock). +pub(crate) fn preparing(number: u64) { + PREPARED.store(number, Ordering::Relaxed); +} + +/// With [`relay`]: the number of the last send of changed ranges to the +/// card (`crate::host`'s order of the queue) that every fetch still to be +/// merged came after. Notes of sends up to it are of no use any more. +static RELAY_FETCHED: AtomicU64 = AtomicU64::new(0); + +/// A fetch sent after send `number` is the oldest one that may still be +/// merged ([`RELAY_FETCHED`]). +pub(crate) fn relay_fetched(number: u64) { + RELAY_FETCHED.fetch_max(number, Ordering::AcqRel); +} + +/// With [`relay`]: how many submissions that are not copied back yet +/// declared each range shaders may be writing (range, count, the last +/// submission that declared it). +/// +/// Without it a range declared by two flights was one entry, and the end +/// of the first flight's copy-back removed it while the second was still +/// writing: the next refresh would have put title bytes over what the +/// second flight's shaders were writing. +#[derive(Default)] +struct Flights(Vec<((usize, usize), u32, u64)>); + +impl Flights { + /// Submission `number` declares `range`: counted once for it, however + /// often it declares it. + fn declare(&mut self, range: (usize, usize), number: u64) { + match self.0.iter_mut().find(|f| f.0 == range) { + Some(f) => { + if f.2 != number { + f.1 += 1; + f.2 = number; + } + } + None => self.0.push((range, 1, number)), + } + } + + /// One submission that declared `ranges` (each once) is copied back: + /// the ranges no other submission still holds. + fn done(&mut self, ranges: &[(usize, usize)]) -> Vec<(usize, usize)> { + let mut free = Vec::new(); + for range in ranges { + match self.0.iter().position(|f| f.0 == *range) { + Some(at) => { + self.0[at].1 = self.0[at].1.saturating_sub(1); + if self.0[at].1 == 0 { + self.0.swap_remove(at); + free.push(*range); + } + } + // Not counted (declared before anything counted): free. + None => free.push(*range), + } + } + free + } +} + +/// The relay's merge of a stretch of a copy ([`relay`]). `now` is what the +/// card's memory holds, read once; `held` is the copy's reference for the +/// stretch (its snapshot, or the CPU's side of a copy in the card's +/// memory): what the card's memory held when it was last looked at; +/// `title` is title memory as just read. Every byte the card changed +/// (`now` differs from `held`) goes into `title` and into `held`; every +/// other byte of both stays as it is, so a byte the title wrote and the +/// card did not keeps the title's value. Whether `title` changed. +/// +/// Nothing is stored into `now`'s source: the card may be writing it for a +/// later flight at this moment, and a store there, even of the value just +/// read, could undo that write. (The merge of a waited-for submission +/// stores every byte of a differing stretch back into the copy.) +fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { + let mut differs = 0u8; + for ((n, h), t) in now.iter().zip(held.iter_mut()).zip(title.iter_mut()) { + let wrote = if *n != *h { 0xffu8 } else { 0 }; + let merged = (*t & !wrote) | (*n & wrote); + differs |= merged ^ *t; + *t = merged; + *h = (*h & !wrote) | (*n & wrote); + } + differs != 0 +} + +/// `[from, to)` without the ranges of `skip`, in order. +fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + skip.sort_unstable(); + let mut out = Vec::new(); + let mut at = from; + for (a, b) in skip { + if b <= at { + continue; + } + if a >= to { + break; + } + if a > at { + out.push((at, a)); + } + at = at.max(b); + } + if at < to { + out.push((at, to)); + } + out +} + +#[cfg(test)] +mod relay_tests { + use super::{Flights, changed_runs, merge_piece, outside}; + + /// A range two flights declared is free only when both are done, in + /// either order; a submission that declares it many times counts once. + #[test] + fn a_range_stays_closed_until_every_flight_that_declared_it_is_done() { + let (a, b) = ((0x1000, 0x2000), (0x1800, 0x3000)); + let mut flights = Flights::default(); + for _ in 0..3 { + flights.declare(a, 7); + } + flights.declare(b, 7); + flights.declare(a, 8); + // Flight 7 lands: `a` is still flight 8's, `b` was only flight 7's. + assert_eq!(flights.done(&[a, b]), vec![b]); + // Declared again meanwhile by a third. + flights.declare(a, 9); + assert_eq!(flights.done(&[a]), vec![]); + assert_eq!(flights.done(&[a]), vec![a]); + assert!(flights.0.is_empty()); + // The later flight first: the same. + flights.declare(a, 1); + flights.declare(a, 2); + assert_eq!(flights.done(&[a]), vec![]); + assert_eq!(flights.done(&[a]), vec![a]); + // A range never counted is free at once. + assert_eq!(flights.done(&[b]), vec![b]); + } + + /// The merge moves exactly the bytes the card changed, into title + /// memory and into the reference, and stores nothing else. + #[test] + fn the_merge_stores_only_what_the_card_changed() { + let held0: Vec = (0..200u32).map(|i| (i * 5 + 1) as u8).collect(); + let mut now = held0.clone(); + for at in [0usize, 3, 4, 5, 64, 199] { + now[at] ^= 0x33; + } + // The title wrote other bytes meanwhile, and one the card wrote too. + let mut title = held0.clone(); + for at in [1usize, 5, 100] { + title[at] = 0xee; + } + let title0 = title.clone(); + let mut held = held0.clone(); + assert!(merge_piece(&now, &mut held, &mut title)); + for at in 0..200 { + if now[at] != held0[at] { + assert_eq!((title[at], held[at]), (now[at], now[at]), "the card's byte at {at}"); + } else { + assert_eq!((title[at], held[at]), (title0[at], held0[at]), "untouched at {at}"); + } + } + // Again with nothing new: nothing changes and nothing is reported. + let (title1, held1) = (title.clone(), held.clone()); + assert!(!merge_piece(&now, &mut held, &mut title)); + assert_eq!((title, held), (title1, held1)); + } + + #[test] + fn ranges_are_cut_out() { + assert_eq!(outside(10, 50, vec![]), vec![(10, 50)]); + assert_eq!(outside(10, 50, vec![(0, 10), (50, 60)]), vec![(10, 50)]); + assert_eq!(outside(10, 50, vec![(30, 35), (0, 12), (34, 40), (48, 99)]), vec![(12, 30), (40, 48)]); + assert_eq!(outside(10, 50, vec![(0, 99)]), vec![]); + } + + /// A model of a copy in the PC's memory under the relay: the card + /// writes `copy` directly; `snap` is the snapshot; `title` is title + /// memory. Flight A and flight B declare overlapping ranges and both + /// are in the air; the title's CPU writes in between and its bytes are + /// put in beside the flights' (`merge_under_writes`: into the copy and + /// the snapshot); A lands while B is still writing; then B lands. + #[test] + fn two_flights_overlapping_ranges_and_a_cpu_write_in_between() { + const N: usize = 64; + let base: Vec = (0..N as u32).map(|i| i as u8).collect(); + let (mut copy, mut title) = (base.clone(), base.clone()); + // A declares [0, 40), B declares [24, 64): each byte's snapshot is + // taken when the first range that holds it is declared. + let (a, b) = ((0usize, 40usize), (24usize, 64usize)); + let mut snap = base.clone(); + // The card runs A: writes 4..12 and 30..34. + for at in (4..12).chain(30..34) { + copy[at] = 0xa0; + } + // The title's CPU writes 8..10 (over A's bytes), 20 and 50, after + // A's refresh: the next submission's preparing finds them against + // the snapshot and puts them in, into the copy and the snapshot. + for at in [8usize, 9, 20, 50] { + title[at] = 0x77; + } + for (at, n) in changed_runs(&title, &snap) { + copy[at..at + n].copy_from_slice(&title[at..at + n]); + snap[at..at + n].copy_from_slice(&title[at..at + n]); + } + // The card starts B: it has written 32..36 so far, over A's 32..34. + for at in 32..36 { + copy[at] = 0xb0; + } + // A lands (B still on the card): its range is merged. The copy is + // read once and not written. + let seen = copy.clone(); + { + let mut t = title[a.0..a.1].to_vec(); + assert!(merge_piece(&seen[a.0..a.1], &mut snap[a.0..a.1], &mut t)); + title[a.0..a.1].copy_from_slice(&t); + } + assert_eq!(copy, seen, "the merge stores nothing into the copy"); + // A's bytes are in title memory, except where the title wrote + // after A's shaders did (8, 9: the title's); B's first bytes came + // along; nothing of B's range beyond A's was touched. + for at in (4..8).chain(10..12).chain(30..32) { + assert_eq!(title[at], 0xa0, "A's byte at {at}"); + } + assert_eq!((title[8], title[9], title[20], title[50]), (0x77, 0x77, 0x77, 0x77)); + for at in 32..36 { + assert_eq!(title[at], 0xb0, "B's byte so far at {at}"); + } + // The card finishes B: 36..44. + for at in 36..44 { + copy[at] = 0xb1; + } + // The title's CPU writes 40 after B's shader did: found against + // the snapshot at the next preparing, which is before B lands. + title[40] = 0x55; + for (at, n) in changed_runs(&title[b.0..b.1], &snap[b.0..b.1]) { + let at = at + b.0; + copy[at..at + n].copy_from_slice(&title[at..at + n]); + snap[at..at + n].copy_from_slice(&title[at..at + n]); + } + // B lands. + let seen = copy.clone(); + { + let mut t = title[b.0..b.1].to_vec(); + assert!(merge_piece(&seen[b.0..b.1], &mut snap[b.0..b.1], &mut t)); + title[b.0..b.1].copy_from_slice(&t); + } + // B's results are there, never replaced by A's older ones. + for at in 32..36 { + assert_eq!(title[at], 0xb0); + } + for at in (36..40).chain(41..44) { + assert_eq!(title[at], 0xb1, "B's byte at {at}"); + } + assert_eq!(title[40], 0x55, "the title wrote it last"); + // In the declared ranges the copy, the snapshot and title memory + // now agree byte for byte: nothing is left to hand back, and + // nothing was lost. + assert_eq!(copy[a.0..b.1], title[a.0..b.1]); + assert_eq!(snap[a.0..b.1], title[a.0..b.1]); + // A third merge finds nothing. + let mut t = title.clone(); + assert!(!merge_piece(©, &mut snap, &mut t)); + } + + /// A model of a copy in the card's memory under the relay: `card` is + /// the card's side, `cpu` the CPU's side, `title` title memory. The + /// title's changed bytes go into the CPU's side at once and up to the + /// card with a later send; pieces fetched before that send must not + /// take the card's older bytes there for something the card wrote. + #[test] + fn title_bytes_not_yet_on_the_card_are_not_taken_for_shader_writes() { + const N: usize = 48; + let base: Vec = (0..N as u32).map(|i| (i + 100) as u8).collect(); + let (mut card, mut cpu, mut title) = (base.clone(), base.clone(), base.clone()); + // Flight A's shaders write 10..14 on the card. + for at in 10..14 { + card[at] = 0xa0; + } + // The title's CPU writes 12 (over A's) and 30; the preparing of + // the next submission puts both into the CPU's side and notes them + // to go up (send 5). They are not on the card yet. + title[12] = 0x77; + title[30] = 0x78; + let mut noted = Vec::new(); + for (at, n) in changed_runs(&title, &cpu) { + cpu[at..at + n].copy_from_slice(&title[at..at + n]); + noted.push((at, at + n, 5u64)); + } + // A's pieces are fetched after send 4, before send 5: the fetch + // holds A's bytes and the card's old bytes at 12 and 30. + let fetched = card.clone(); + let fetched_after = 4u64; + // Send 5 goes up behind it. + for &(a, b, _) in ¬ed { + card[a..b].copy_from_slice(&cpu[a..b]); + } + // The merge leaves out what went up after the fetch. + let skip: Vec<(usize, usize)> = noted.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1)).collect(); + let mut changed = false; + for (a, b) in outside(0, N, skip) { + let mut t = title[a..b].to_vec(); + changed |= merge_piece(&fetched[a..b], &mut cpu[a..b], &mut t); + title[a..b].copy_from_slice(&t); + } + assert!(changed); + // A's bytes arrived; the title's two writes stand, in title memory + // and on both sides of the copy. + for at in [10usize, 11, 13] { + assert_eq!((title[at], cpu[at]), (0xa0, 0xa0)); + } + assert_eq!((title[12], cpu[12], card[12]), (0x77, 0x77, 0x77)); + assert_eq!((title[30], cpu[30], card[30]), (0x78, 0x78, 0x78)); + assert_eq!(card, cpu); + assert_eq!(card, title); + // Without the leaving out, the card's old byte at 30 would have + // been taken for a shader write and put over the title's. + let mut wrong_title = title.clone(); + let mut wrong_cpu = cpu.clone(); + merge_piece(&fetched, &mut wrong_cpu, &mut wrong_title); + assert_eq!(wrong_title[30], base[30]); + } } /// Snapshot memory kept for reuse (already touched, so no page faults). static POOL: Mutex>> = Mutex::new(Vec::new()); -/// An empty buffer with room for `n` bytes, from the pool if it has one. +/// An empty buffer with room for `n` bytes, from the pool if it has one +/// of about that size: a small copy's snapshot took the 174 MB buffer kept +/// for the big heap's, which then got another, until eight of them were +/// reserved (1.4 GB in run 24). fn pooled(n: usize) -> Vec { let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let most = n.saturating_mul(4).max(1 << 20); let fit = pool .iter() .enumerate() - .filter(|(_, v)| v.capacity() >= n) + .filter(|(_, v)| v.capacity() >= n && v.capacity() <= most) .min_by_key(|(_, v)| v.capacity()) .map(|(i, _)| i); let mut v = match fit { @@ -67,18 +839,807 @@ fn pooled(n: usize) -> Vec { v } -/// Returns a snapshot buffer to the pool (at most 8 kept, the largest). +/// Returns a snapshot buffer to the pool: at most 8 kept, the largest, and +/// of those the largest one and the next ones up to `KEPT` bytes in all. fn give_back(v: Vec) { + const KEPT: usize = 512 << 20; let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); pool.push(v); - if pool.len() > 8 { - pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); - pool.truncate(8); - } + pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); + pool.truncate(8); + let (mut seen, mut total) = (0, 0usize); + pool.retain(|v| { + seen += 1; + total = total.saturating_add(v.capacity()); + seen == 1 || total <= KEPT + }); } const NOT_WATCHED: u8 = 2; +/// Where `a` and `b` (of one length) first differ, compared eight bytes at +/// a time. +fn first_difference(a: &[u8], b: &[u8]) -> Option { + let whole = a.len().min(b.len()) / 8 * 8; + let from = a[..whole] + .as_chunks::<8>().0.iter() + .zip(b[..whole].chunks_exact(8)) + .position(|(x, y)| x != y) + .map_or(whole, |word| word * 8); + a[from..].iter().zip(&b[from..]).position(|(x, y)| x != y).map(|i| from + i) +} + +/// Where `a` and `b` (of one length) last differ. +fn last_difference(a: &[u8], b: &[u8]) -> Option { + let whole = a.len().min(b.len()) / 8 * 8; + if let Some(i) = a[whole..].iter().zip(&b[whole..]).rposition(|(x, y)| x != y) { + return Some(whole + i); + } + let word = a[..whole] + .as_chunks::<8>().0.iter() + .zip(b[..whole].chunks_exact(8)) + .rposition(|(x, y)| x != y)? + * 8; + a[word..word + 8] + .iter() + .zip(&b[word..word + 8]) + .rposition(|(x, y)| x != y) + .map(|i| word + i) +} + +#[cfg(test)] +mod difference_tests { + use super::{first_difference, last_difference}; + + /// The word-wise searches agree with the byte-wise ones they replace. + #[test] + fn differences_are_found_as_byte_by_byte() { + let base: Vec = (0..61u32).map(|i| (i * 7 + 3) as u8).collect(); + let same = base.clone(); + assert_eq!(first_difference(&base, &same), None); + assert_eq!(last_difference(&base, &same), None); + for len in [0usize, 1, 7, 8, 9, 16, 23, 61] { + for at in 0..len { + for other in at..len { + let (a, mut b) = (&base[..len], base[..len].to_vec()); + b[at] ^= 0x80; + b[other] ^= 0x01; + let first = a.iter().zip(&b).position(|(x, y)| x != y); + let last = a.iter().zip(&b).rposition(|(x, y)| x != y); + assert_eq!(first_difference(a, &b), first, "{len} {at} {other}"); + assert_eq!(last_difference(a, &b), last, "{len} {at} {other}"); + } + } + } + } +} + +/// The unit shader writes are looked for and put back in. +const PIECE: usize = 64 << 10; + +/// Copies `len` bytes, on several threads if they are many: a snapshot of +/// the world's big heap is 100-170 MB per submission, 2-4 GB a frame, and +/// one thread copies some 8 GB/s. +/// +/// # Safety +/// Both ranges are valid for `len` bytes and do not overlap. +unsafe fn copy_wide(src: *const u8, dst: *mut u8, len: usize) { + const PER_THREAD: usize = 16 << 20; + let threads = (len / PER_THREAD).clamp(1, 6); + if threads == 1 { + // SAFETY: the caller's. + unsafe { std::ptr::copy_nonoverlapping(src, dst, len) }; + return; + } + let (src, dst, each) = (src as usize, dst as usize, len.div_ceil(threads)); + std::thread::scope(|s| { + for i in 0..threads { + let at = (i * each).min(len); + let n = each.min(len - at); + s.spawn(move || { + // SAFETY: a part of the caller's ranges. + unsafe { std::ptr::copy_nonoverlapping((src + at) as *const u8, (dst + at) as *mut u8, n) }; + }); + } + }); +} + +/// Whether the snapshots of a submission's shader-written ranges, and the +/// compare that finds what the shaders wrote, run on several threads +/// across ranges (`VICTORY_WIDE_BACK=1`; off by default). +/// +/// Both ran range by range on the submitting thread, a range on several +/// threads only if it was 16 MiB or more. The ranges left on the CPU's side +/// since the big buffers went to the card are small and many: in run 86, +/// 7,024 declared ranges a frame, 375 MB of them compared after the card +/// ran in 563 pieces of work, none of 16 MiB: 51 ms a frame of snapshots +/// and 35 ms of comparing, one thread, bound by one core's memory speed. +/// +/// With the switch a submission's snapshots are noted as it is prepared +/// and taken together when its refreshes are done, just before it goes to +/// the card ([`take_snapshots`]), and the compares of everything declared +/// run together after the card ([`find_all`]), both cut into pieces of +/// work of about 1 MiB for a few threads that are kept ([`wide`]). The +/// bytes taken and the bytes compared are the same ones: a range's bytes +/// cannot change between the moment it is declared and the end of the +/// preparing (a declared range is left alone by every refresh, the title's +/// own copies write title memory and not the copy, and the card runs the +/// lists only afterwards). +pub(crate) fn wide_back() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + // On by default; `VICTORY_WIDE_BACK=0` turns it off. + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_BACK").is_none_or(|v| v != "0")) +} + +type Job = Box; + +/// Threads kept for [`wide`]: what they are to do, and the word that there +/// is something. +struct Workers { + jobs: Mutex>, + more: std::sync::Condvar, +} + +fn workers() -> &'static Workers { + static WORKERS: std::sync::OnceLock = std::sync::OnceLock::new(); + static STARTED: std::sync::Once = std::sync::Once::new(); + let workers = WORKERS.get_or_init(|| Workers { + jobs: Mutex::new(std::collections::VecDeque::new()), + more: std::sync::Condvar::new(), + }); + STARTED.call_once(|| { + let n = std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6); + for i in 0..n { + let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || { + let workers = WORKERS.get().expect("made above"); + loop { + let job = { + let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(job) = jobs.pop_front() { + break job; + } + jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner()); + } + }; + job(); + } + }); + } + }); + workers +} + +/// Runs `jobs` on the kept threads and on this one, and returns when all +/// of them are done. The jobs copy and compare memory; they do not panic. +fn wide(jobs: Vec) { + if jobs.len() < 2 { + for job in jobs { + job(); + } + return; + } + let workers = workers(); + let left = Arc::new((Mutex::new(jobs.len()), std::sync::Condvar::new())); + { + let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); + for job in jobs { + let left = left.clone(); + queue.push_back(Box::new(move || { + job(); + let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner()); + *n -= 1; + if *n == 0 { + left.1.notify_all(); + } + })); + } + } + workers.more.notify_all(); + loop { + let job = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()).pop_front(); + match job { + Some(job) => job(), + None => break, + } + } + let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner()); + while *n > 0 { + n = left.1.wait(n).unwrap_or_else(|e| e.into_inner()); + } +} + +/// [`wide`], for the host's own work on host copies (a submission's +/// refreshes, the merge of what shaders wrote to card copies). +pub(crate) fn wide_run(jobs: Vec>) { + wide(jobs); +} + +/// About this many bytes to a piece of work for [`wide`]. +const WIDE_JOB: usize = 1 << 20; + +/// With [`wide_back`]: the snapshots noted while a submission is prepared +/// (from, to, bytes), taken by [`take_snapshots`]. +static SNAPS: Mutex> = Mutex::new(Vec::new()); + +/// With [`wide_back`], when a submission's refreshes are done and before +/// its lists go to the card: takes the snapshots [`Shadow::writing`] noted. +/// Nothing to do without the switch. +pub(crate) fn take_snapshots() { + let snaps = std::mem::take(&mut *SNAPS.lock().unwrap_or_else(|e| e.into_inner())); + if snaps.is_empty() { + return; + } + wide(copy_jobs(snaps)); +} + +/// `copies` (from, to, bytes) as pieces of work of about [`WIDE_JOB`] +/// bytes each: long ones cut, short ones together. +fn copy_jobs(copies: Vec<(usize, usize, usize)>) -> Vec { + let mut jobs: Vec = Vec::new(); + let mut group: Vec<(usize, usize, usize)> = Vec::new(); + let mut bytes = 0; + let flush = |group: &mut Vec<(usize, usize, usize)>, jobs: &mut Vec| { + let group = std::mem::take(group); + if !group.is_empty() { + jobs.push(Box::new(move || { + for (src, dst, len) in group { + // SAFETY: the caller's ranges: a host copy's mapping and + // its snapshot, which do not overlap. + unsafe { std::ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, len) }; + } + })); + } + }; + for (src, dst, len) in copies { + let mut at = 0; + while at < len { + let n = (WIDE_JOB - bytes).min(len - at); + group.push((src + at, dst + at, n)); + at += n; + bytes += n; + if bytes >= WIDE_JOB { + flush(&mut group, &mut jobs); + bytes = 0; + } + } + } + flush(&mut group, &mut jobs); + jobs +} + +/// With [`wide_back`]: for each of `work` (a copy not in the card's memory +/// and a range `[address, end)` its shaders may have written, declared and +/// not yet done), the 64 KiB pieces that differ from the snapshot, as +/// [`Shadow::copy_back_with`] takes them; found on several threads. +pub(crate) fn find_all(work: &[(Arc, usize, usize)]) -> Vec> { + let scans = work + .iter() + .map(|(shadow, address, end)| { + let (from, to) = shadow.inside(*address, end.saturating_sub(*address)); + // The snapshot's memory stays until the range is done with + // (`copy_back_done`), which comes after this. + match shadow.before.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { + Some(before) => (shadow.data as usize, before.as_ptr() as usize, shadow.start as usize, from, to), + None => (0, 0, 0, 0, 0), + } + }) + .collect(); + find_pieces(scans) +} + +/// For each of `scans` (where a copy's bytes are, where its snapshot's +/// are, the title address the copy starts at, offsets from and to): the +/// 64 KiB pieces (cut at multiples of 64 KiB of title memory, as +/// [`Shadow::differing`] cuts them) of `[from, to)` whose bytes differ, as +/// (offset, bytes) in order. On several threads ([`wide`]), in pieces of +/// work of about [`WIDE_JOB`] bytes that hold whole pieces. +fn find_pieces(scans: Vec<(usize, usize, usize, usize, usize)>) -> Vec> { + // What a job finds: (which scan, its place among that scan's jobs, the + // pieces). + type Found = Vec<(usize, usize, Vec<(usize, usize)>)>; + // A job's part of a scan: the scan, then which and place. + type Part = (usize, usize, usize, usize, usize, usize, usize); + let found: Arc> = Arc::default(); + let mut jobs: Vec = Vec::new(); + let mut group: Vec = Vec::new(); + let mut bytes = 0; + let flush = |group: &mut Vec, jobs: &mut Vec| { + let group = std::mem::take(group); + if group.is_empty() { + return; + } + let found = found.clone(); + jobs.push(Box::new(move || { + let mut mine: Found = Vec::with_capacity(group.len()); + for (data, before, start, from, to, which, place) in group { + let mut pieces = Vec::new(); + let mut at = from; + while at < to { + let n = (PIECE - (start + at) % PIECE).min(to - at); + // SAFETY: inside the copy's mapping and its snapshot + // (which holds the copy's bytes at the copy's offsets); + // nothing writes either while a submission's results + // are compared. + let (now, old) = unsafe { + ( + std::slice::from_raw_parts((data + at) as *const u8, n), + std::slice::from_raw_parts((before + at) as *const u8, n), + ) + }; + if now != old { + pieces.push((at, n)); + } + at += n; + } + mine.push((which, place, pieces)); + } + found.lock().unwrap_or_else(|e| e.into_inner()).extend(mine); + })); + }; + let count = scans.len(); + for (which, (data, before, start, from, to)) in scans.into_iter().enumerate() { + let (mut at, mut place) = (from, 0); + while at < to { + // Cut where pieces end, so that every job sees whole pieces. + let room = (WIDE_JOB - bytes).max(PIECE); + let mut next = (at + room).min(to); + if next < to { + next -= (start + next) % PIECE; + if next <= at { + next = (at + PIECE - (start + at) % PIECE).min(to); + } + } + group.push((data, before, start, at, next, which, place)); + bytes += next - at; + place += 1; + at = next; + if bytes >= WIDE_JOB { + flush(&mut group, &mut jobs); + bytes = 0; + } + } + } + flush(&mut group, &mut jobs); + wide(jobs); + let mut found = std::mem::take(&mut *found.lock().unwrap_or_else(|e| e.into_inner())); + found.sort_unstable_by_key(|f| (f.0, f.1)); + let mut out = vec![Vec::new(); count]; + for (which, _, pieces) in found { + out[which].extend(pieces); + } + out +} + +/// Since the last frame-rate line, of the shader-written ranges looked for +/// on the CPU (copies not in the card's memory): bytes snapshotted in +/// windows outside buffers and in title buffers' copies; bytes compared in +/// windows, in buffers' copies, and of those in copies of 1 MiB or more; +/// ranges compared in windows and in buffers' copies. +static BACK_CLASS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + +/// For the frame-rate line: where the CPU's search for shader writes goes +/// (per frame). A copy of a title buffer can go to the card's memory, +/// where the card does the search (`VICTORY_CARD_BUFFERS_MIN_MB`); a +/// window outside buffers cannot as the code stands. +pub(crate) fn back_line(frames: f64) { + let c: Vec = BACK_CLASS.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if c.iter().all(|&v| v == 0.0) { + return; + } + let mb = |v: f64| v / (1 << 20) as f64; + tracing::info!( + "shader writes looked for on the CPU per frame: {:.1} MB compared in {:.0} ranges of windows outside buffers ({:.1} MB \ + snapshotted), {:.1} MB in {:.0} ranges of title buffers' copies ({:.1} MB snapshotted), of them {:.1} MB in copies \ + of 1 MiB or more (VICTORY_CARD_BUFFERS_MIN_MB=1 would have the card look there)", + mb(c[2]), + c[5], + mb(c[0]), + mb(c[3]), + c[6], + mb(c[1]), + mb(c[4]), + ); +} + +#[cfg(test)] +mod wide_tests { + use super::{Job, PIECE, WIDE_JOB, copy_jobs, find_pieces, wide}; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Every job runs once, however many there are, and `wide` returns + /// only when all have. + #[test] + fn all_jobs_run_before_wide_returns() { + for n in [0usize, 1, 2, 7, 300] { + let ran = Arc::new(AtomicUsize::new(0)); + let jobs: Vec = (0..n) + .map(|i| { + let ran = ran.clone(); + Box::new(move || { + ran.fetch_add(i + 1, Ordering::Relaxed); + }) as Job + }) + .collect(); + wide(jobs); + assert_eq!(ran.load(Ordering::Relaxed), n * (n + 1) / 2, "{n} jobs"); + } + } + + /// Copies cut into jobs copy every byte once: long ones, short ones + /// and empty ones. + #[test] + fn copies_cut_into_jobs_copy_the_same_bytes() { + let len = 3 * WIDE_JOB + 12345; + let src: Vec = (0..len).map(|i| (i * 31 + i / 977) as u8).collect(); + let mut dst = vec![0u8; len]; + let (s, d) = (src.as_ptr() as usize, dst.as_mut_ptr() as usize); + // Ranges of the buffer, each to the same offsets of the other. + let cuts = [0, 1, 1, 4096, 70_000, WIDE_JOB + 3, 2 * WIDE_JOB + 3, 2 * WIDE_JOB + 9, len]; + let copies: Vec<(usize, usize, usize)> = cuts.windows(2).map(|w| (s + w[0], d + w[0], w[1] - w[0])).collect(); + let jobs = copy_jobs(copies); + assert!(jobs.len() >= 3); + wide(jobs); + assert!(src == dst); + } + + /// The pieces found on several threads are the ones a walk piece by + /// piece finds, for copies that start anywhere in a 64 KiB piece of + /// title memory and ranges that start and end anywhere. + #[test] + fn pieces_found_wide_are_those_found_one_by_one() { + let len = 5 * WIDE_JOB / 2 + 777; + let old: Vec = (0..len).map(|i| (i * 7 + i / 513) as u8).collect(); + let mut now = old.clone(); + // Changes: single bytes at piece edges, a run across two pieces, + // the last byte, and nothing in between. + for at in [0usize, 1, PIECE - 1, PIECE, 3 * PIECE + 5, WIDE_JOB - 1, WIDE_JOB, WIDE_JOB + PIECE / 2, 2 * WIDE_JOB + 9, len - 1] { + now[at] ^= 0x5a; + } + for byte in &mut now[9 * PIECE - 40..9 * PIECE + 40] { + *byte ^= 0x01; + } + let (data, before) = (now.as_ptr() as usize, old.as_ptr() as usize); + let mut scans = Vec::new(); + let mut wanted = Vec::new(); + for start in [0usize, 4096, PIECE - 16, 0xd_b790_df00] { + for (from, to) in [(0, len), (0, 1), (1, 2), (PIECE - 1, PIECE + 1), (3 * PIECE, 3 * PIECE), (12345, len - 1), (WIDE_JOB - 3, 2 * WIDE_JOB + 10)] { + scans.push((data, before, start, from, to)); + let mut pieces = Vec::new(); + let mut at = from; + while at < to { + let n = (PIECE - (start + at) % PIECE).min(to - at); + if now[at..at + n] != old[at..at + n] { + pieces.push((at, n)); + } + at += n; + } + wanted.push(pieces); + } + } + // A scan of nothing (a range whose snapshot is gone). + scans.push((0, 0, 0, 0, 0)); + wanted.push(Vec::new()); + assert_eq!(find_pieces(scans), wanted); + } +} + +/// Since the last frame-rate line, of [`Shadow::merge_under_writes`]: pages +/// compared, changed runs put in, and their bytes. +static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// [`MERGED`], taken. +pub(crate) fn merged_stats() -> [u64; 3] { + [0, 1, 2].map(|i| MERGED[i].swap(0, Ordering::Relaxed)) +} + +/// The runs of bytes where `now` differs from `was` (of one length), as +/// (offset, bytes) in order: every differing byte is in a run and no equal +/// byte is. +fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { + let n = now.len().min(was.len()); + let mut runs = Vec::new(); + let mut i = 0; + while i < n { + // Equal bytes, eight at a time while they last. + while i + 8 <= n && now[i..i + 8] == was[i..i + 8] { + i += 8; + } + while i < n && now[i] == was[i] { + i += 1; + } + if i >= n { + break; + } + let first = i; + while i < n && now[i] != was[i] { + i += 1; + } + runs.push((first, i - first)); + } + runs +} + +#[cfg(test)] +mod merge_tests { + use super::changed_runs; + + /// The runs hold exactly the bytes that differ: putting them into the + /// old bytes gives the new ones, and no run holds an equal byte. + #[test] + fn changed_runs_are_exactly_the_bytes_that_differ() { + let was: Vec = (0..300u32).map(|i| (i * 13 + 5) as u8).collect(); + for changes in [vec![], vec![0], vec![299], vec![7, 8, 9], vec![7, 9], vec![15, 16, 17, 23, 24, 64, 65, 66, 67, 68, 69, 70, 71, 72, 298, 299]] { + let mut now = was.clone(); + for &at in &changes { + now[at] ^= 0x41; + } + let runs = changed_runs(&now, &was); + let mut put = was.clone(); + let mut held = Vec::new(); + for &(at, n) in &runs { + assert!(n > 0); + put[at..at + n].copy_from_slice(&now[at..at + n]); + held.extend(at..at + n); + } + assert_eq!(put, now, "{changes:?}"); + assert_eq!(held, changes, "{changes:?}"); + // Runs do not touch: two that did would be one. + assert!(runs.windows(2).all(|w| w[0].0 + w[0].1 < w[1].0), "{changes:?}"); + } + assert!(changed_runs(&[], &[]).is_empty()); + } +} + +/// Host copies alive (also those only a list, a descriptor pass or a +/// snapshot still holds) and the bytes of title memory they copy. +static LIVE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +impl Drop for Shadow { + fn drop(&mut self) { + if self.place.is_some() { + // Never counted with the copies (`Shadow::placed`). + crate::inplace::gone(self.window, self.len); + return; + } + LIVE[0].fetch_sub(1, Ordering::Relaxed); + LIVE[1].fetch_sub(self.len, Ordering::Relaxed); + if self.kept.get_mut().unwrap_or_else(|e| e.into_inner()).1 { + KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed); + } + let window = self.window; + if let Some(card) = &mut self.card { + if window { + WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed); + } else { + CARD_BYTES[0].fetch_sub(card.size, Ordering::Relaxed); + } + if card.before.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() { + CARD_BYTES[1].fetch_sub(card_hash_bytes(card.size), Ordering::Relaxed); + } + } + } +} + +/// Whether a copy's snapshot is kept from one submission to the next and +/// only the pieces that changed in between are taken again +/// (`VICTORY_KEEP_SNAPSHOTS=1`; off by default). +/// +/// A snapshot is the copy's bytes before a submission, to find what its +/// shaders wrote. Taken anew for every submission it is 1,050 MB of copying +/// a frame (72-86 ms in gameplay, runs 61 and 62) for buffers of which +/// 100 MB changed. Kept, a piece of it is taken again only after something +/// changed the copy there: a refresh from title memory ([`Shadow::copy`]), +/// shader writes found after a submission, or the bytes put back then +/// ([`Shadow::copy_back`]). +/// +/// What it assumes, and why it is not on by default: that nothing else +/// writes a copy. A shader that writes a buffer through a view we did not +/// declare as written (we declare the unordered-access views of shaders +/// that can store) changes the copy unseen; with a fresh snapshot that +/// write is simply never put back, with a kept one it would be taken for a +/// write of a later submission and put back then, over whatever the title +/// wrote there since. +fn keeps() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_SNAPSHOTS").is_some_and(|v| v == "1")) +} + +/// Bytes of the snapshots kept, and the most that may be. +static KEPT_BYTES: AtomicU64 = AtomicU64::new(0); +/// `VICTORY_KEEP_SNAPSHOTS_MB`, 256 unless set (it was 768: run 80, with +/// kept snapshots beside copies in the card's memory, ran the PC out of +/// memory in 27 s; kept snapshots are the PC's memory, all of it resident). +fn kept_most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_KEEP_SNAPSHOTS_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(256) << 20 + }) +} + +/// The 64 KiB pieces, cut at multiples of 64 KiB of title memory, that +/// hold offsets `[from, to)` of a copy of memory from `start` on +/// (`from < to`); piece 0 holds offset 0. +fn pieces_of(start: usize, from: usize, to: usize) -> std::ops::Range { + let first = start / PIECE; + (start + from) / PIECE - first..(start + to - 1) / PIECE - first + 1 +} + +/// The offsets that piece `piece` holds of a copy of `len` bytes of memory +/// from `start` on. +fn piece_at(start: usize, len: usize, piece: usize) -> (usize, usize) { + let first = start / PIECE; + let lo = ((first + piece) * PIECE).saturating_sub(start); + let hi = ((first + piece + 1) * PIECE - start).min(len); + (lo, hi) +} + +#[cfg(test)] +mod piece_tests { + use super::{PIECE, piece_at, pieces_of}; + + /// The pieces cover a copy without gaps, each cut where the compare + /// cuts (at multiples of 64 KiB of title memory). + #[test] + fn pieces_cover_the_copy_as_the_compare_cuts_it() { + for start in [0usize, 1, 4096, PIECE - 1, PIECE, PIECE + 77, 5 * PIECE + 12345] { + for len in [1usize, 100, PIECE - 1, PIECE, PIECE + 1, 3 * PIECE + 500] { + let count = pieces_of(start, 0, len).end; + let mut at = 0; + for piece in 0..count { + let (lo, hi) = piece_at(start, len, piece); + assert_eq!(lo, at, "{start} {len} {piece}"); + // As `Shadow::differing` cuts: to the next multiple. + let n = (PIECE - (start + at) % PIECE).min(len - at); + assert_eq!(hi, at + n, "{start} {len} {piece}"); + assert_eq!(pieces_of(start, lo, hi), piece..piece + 1); + assert_eq!(pieces_of(start, hi - 1, hi), piece..piece + 1); + at = hi; + } + assert_eq!(at, len, "{start} {len}"); + assert_eq!(pieces_of(start, 0, len), 0..count); + } + } + } +} + +/// Copies of windows outside buffers let go since the start, and their +/// bytes. +static LET_GO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// For the memory line: the windows let go since the start and their +/// bytes, and of the bytes of the windows alive, how many lie between the +/// lowest and the highest address ever asked for in each. +#[cfg(feature = "diagnostics")] +pub(crate) fn windows() -> [u64; 3] { + let asked: u64 = { + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + loose + .values() + .map(|s| { + let low = s.asked[0].load(Ordering::Relaxed); + let high = s.asked[1].load(Ordering::Relaxed); + high.saturating_sub(low) + }) + .sum() + }; + [LET_GO[0].load(Ordering::Relaxed), LET_GO[1].load(Ordering::Relaxed), asked] +} + +/// For the memory line, of the windows alive: the bytes of their pages +/// ever copied from title memory (the rest of each window is memory the +/// host zeroed and nothing read: what a window made no bigger than what is +/// read would not hold); the windows a descriptor slot shows and their +/// bytes (they stay until the title writes the slot again); the windows a +/// list or a pass over the heap holds and their bytes; the windows asked +/// for without a length (root views, which keep the 4 MiB grid) and their +/// bytes; and the window grid in bytes ([`window`]). +#[cfg(feature = "diagnostics")] +pub(crate) fn window_use() -> [u64; 8] { + let mut out = [0u64; 8]; + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + for s in loose.values() { + let copied = s.copied.lock().unwrap_or_else(|e| e.into_inner()); + let pages = copied.iter().filter(|&&at| at != 0).count() as u64; + out[0] += (pages * PAGE as u64).min(s.len); + if crate::host::references(&s.buffer) > 1 { + out[1] += 1; + out[2] += s.len; + } + if Arc::strong_count(s) > 1 { + out[3] += 1; + out[4] += s.len; + } + if s.unsized_asks.load(Ordering::Relaxed) > 0 { + out[5] += 1; + out[6] += s.len; + } + } + out[7] = window(); + out +} + +/// Lets go of the copies of windows outside buffers that nothing names any +/// more. They were never freed, and the world's streaming keeps asking for +/// new ones: 648 windows (2.8 GB) when the cutscene began, 974 (4.3 GB) +/// eight minutes later (run 24). A window goes when +/// - only the table of windows holds its copy: no list not yet reset reads +/// or writes it, no pass over the heap keeps its range, no submission is +/// comparing it; +/// - only the copy holds its host buffer: no descriptor slot views it (a +/// slot keeps the buffer it views, `HostHeap::kept`), so no draw can read +/// it through a slot made earlier; +/// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames. +/// +/// The next read of that memory makes a new copy and copies the window +/// again. Called before a submission starts, by the thread that submits. +pub(crate) fn let_go_idle() { + const IDLE_FRAMES: u64 = 4; + let gone: Vec> = { + // Held from the look to the removal: `loose` hands a copy out + // under the same lock, so none is handed out in between. + let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + if map.is_empty() { + return; + } + let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + let idle: Vec<(u64, u64)> = map + .iter() + .filter(|(_, s)| { + Arc::strong_count(s) == 1 + && crate::host::long_ago(s.used.load(Ordering::Relaxed), idle_ms, IDLE_FRAMES) + && crate::host::references(&s.buffer) == 1 + }) + .map(|(key, _)| *key) + .collect(); + idle.into_iter().filter_map(|key| map.remove(&key)).collect() + }; + if !gone.is_empty() { + let (went, bytes) = (gone.len(), gone.iter().map(|s| s.len).sum::()); + crate::host::trail(|| { + format!("sweep: {went} host copies of windows of title memory let go ({} KiB), held by no list and no slot", bytes >> 10) + }); + } + for shadow in gone { + LET_GO[0].fetch_add(1, Ordering::Relaxed); + LET_GO[1].fetch_add(shadow.len, Ordering::Relaxed); + // Nothing runs now and nothing names it: freed at once unless a + // submission is running after all. + crate::host::retire(shadow); + } +} + +/// For the memory line: host copies alive and their bytes, of them the +/// windows of memory outside buffers and their bytes, and the snapshot +/// buffers kept for reuse and the bytes they reserve. +#[cfg(feature = "diagnostics")] +pub(crate) fn memory() -> [u64; 6] { + let (windows, window_bytes) = { + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + // Each copy once: a window may stand under several keys. + let mut seen = std::collections::HashSet::new(); + let bytes: u64 = loose + .values() + .filter(|s| seen.insert(Arc::as_ptr(s) as usize)) + .map(|s| s.len) + .sum(); + (seen.len() as u64, bytes) + }; + let (kept, kept_bytes) = { + let pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + (pool.len() as u64, pool.iter().map(|v| v.capacity() as u64).sum::()) + }; + [ + LIVE[0].load(Ordering::Relaxed), + LIVE[1].load(Ordering::Relaxed), + windows, + window_bytes, + kept, + kept_bytes, + ] +} + // SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping // written only on the submitting thread. unsafe impl Send for Shadow {} @@ -91,19 +1652,52 @@ impl Shadow { self.gpu + (address - self.start) } + /// The title memory the copy is of: its start and length. + pub(crate) fn span(&self) -> (u64, u64) { + (self.start, self.len) + } + + /// The offset of a title address in the copy, if it lies in it. + pub(crate) fn offset_in(&self, address: u64) -> Option { + address.checked_sub(self.start).filter(|&at| at < self.len) + } + /// Bytes from a title address to the buffer's end. pub(crate) fn left(&self, address: u64) -> u64 { (self.start + self.len).saturating_sub(address) } + /// Whether the memory behind the copy turned out not to be write-watched: + /// every refresh then copies its whole range. + pub(crate) fn unwatched(&self) -> bool { + self.watched.load(Ordering::Relaxed) == NOT_WATCHED + } + + /// The copy's own number (see the field). + pub(crate) fn id(&self) -> u64 { + self.id + } + /// 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.place.as_ref().map_or(0, |place| place.1) } - /// The title memory the copy holds: its first address and length. - pub(crate) fn span(&self) -> (u64, u64) { - (self.start, self.len) + /// Title memory `[start, start + len)` in place: `placed` is a buffer + /// over it in a heap opened on it. Shaped as a copy so that everything + /// that binds, views or keeps a copy works on it unchanged; what + /// copies does nothing ([`Shadow::update`], [`Shadow::gpu_writes`]). + fn placed(placed: crate::inplace::Placed, start: u64, len: u64, window: bool) -> Shadow { + crate::host::name(&placed.buffer, || format!("title memory {start:#x}+{len:#x} in place")); + let mut shadow = Shadow::new(placed.buffer, start as *mut u8, placed.gpu, start, len); + // Not a copy: not counted with them, and nothing asks what the + // title wrote there. + LIVE[0].fetch_sub(1, Ordering::Relaxed); + LIVE[1].fetch_sub(len, Ordering::Relaxed); + *shadow.watched.get_mut() = NOT_WATCHED; + shadow.window = window; + shadow.place = Some((placed.heap, placed.bias)); + shadow } /// Brings `len` bytes at `address` up to date when `list` is submitted, @@ -115,9 +1709,10 @@ impl Shadow { fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow { let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64; + LIVE[0].fetch_add(1, Ordering::Relaxed); + LIVE[1].fetch_add(len, Ordering::Relaxed); Shadow { buffer, - state: AtomicU32::new(0), data, gpu, start, @@ -125,167 +1720,649 @@ impl Shadow { copied: Mutex::new(vec![0; pages as usize]), watched: AtomicU8::new(0), pending: Mutex::default(), + flights: Mutex::default(), before: Mutex::default(), + kept: Mutex::default(), + used: AtomicU64::new(crate::host::moment()), + asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)], + unsized_asks: AtomicU64::new(0), + id: { + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) + }, + card: None, + window: false, + place: None, + } + } + + /// `[address, address + len)` cut to the buffer, as offsets in the copy. + fn inside(&self, address: usize, len: usize) -> (usize, usize) { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let from = address.clamp(start, end); + (from - start, (address + len).clamp(from, end) - start) + } + + /// Shaders of `list` may write `[address, address + len)` of the copy + /// (unordered access): after the list's submission has run, the range + /// is copied back into title memory, where the title reads it; until + /// then no refresh copies title memory over it. Call after the + /// [`Shadow::refresh`] that gives the shaders the title's data. + /// + /// shortcut: what shaders wrote is found by keeping the range's bytes + /// before the submission (a copy per declared range and submission); + /// a GPU-side dirty mask would save that if big ranges make it slow. + pub(crate) fn gpu_writes(self: &Arc, list: &HostList, address: u64, len: u64) { + // In place the shaders write title memory itself: no snapshot, no + // compare, nothing to copy back, and no wait on its account. + // shortcut: another host copy of the same bytes (a title buffer + // inside this one with a copy of its own, a texture in it) is not + // told: the card's writes are not seen by write watching. + if self.place.is_some() { + return; + } + let len = len.min(self.left(address)); + list.defer_gpu_write(self, address as usize, len as usize); + } + + /// At submission, after the range's refresh: a submitted list's shaders + /// write this range. Its bytes are kept to tell later what the GPU wrote: + /// one snapshot per copy and submission, each byte taken once, when the + /// first range holding it is declared (the world declares overlapping + /// views of its 174 MB heap dozens of times, from different offsets: a + /// snapshot grown to cover each was copied whole every time), in reused + /// memory (fresh snapshots cost ~2.3 million page faults per world + /// frame). + pub(crate) fn writing(&self, address: usize, len: usize) { + if self.place.is_some() { + return; + } + let range = (address, address + len); + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + // With the copy-back on its own thread: counted for this submission + // (once), whether or not an earlier one still holds the range. + if relay() { + self.flights.lock().unwrap_or_else(|e| e.into_inner()).declare(range, PREPARED.load(Ordering::Relaxed)); + } + // Dispatches declare the same ranges thousands of times. + if pending.contains(&range) { + return; + } + // In the card's memory: no snapshot. What shaders wrote is found on + // the card (`Host::card_before` reads the declared ranges from the + // lists). + if self.card.is_some() { + pending.push(range); + return; + } + // The parts no declared range holds yet: their bytes are taken now, + // just after the range's refresh (a part declared earlier has not + // been refreshed since, and keeps the bytes taken then). + let mut parts = vec![self.inside(address, len)]; + for &(a, e) in pending.iter() { + let (a, e) = self.inside(a, e - a); + let mut rest = Vec::with_capacity(parts.len() + 1); + for (from, to) in parts { + if e <= from || a >= to { + rest.push((from, to)); + continue; + } + if from < a { + rest.push((from, a)); + } + if e < to { + rest.push((e, to)); + } + } + parts = rest; + } + pending.push(range); + let taken: usize = parts.iter().map(|&(from, to)| to.saturating_sub(from)).sum(); + BACK_CLASS[usize::from(!self.window)].fetch_add(taken as u64, Ordering::Relaxed); + let total = self.len as usize; + let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let snapshot = before.get_or_insert_with(|| pooled(total)); + if keeps() { + // Piece by piece, and only the pieces not known current. A + // piece the part holds whole is current from now on; of a + // piece it holds partly only the part's bytes are taken, as + // without the switch, and it is taken again next time (the + // rest of it may belong to a range declared earlier, whose + // bytes stay as they were taken). + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if kept.0.is_empty() { + kept.0 = vec![false; self.pieces(0, total.max(1)).end]; + } + for (from, to) in parts { + if from >= to { + continue; + } + for piece in self.pieces(from, to) { + if kept.0[piece] { + continue; + } + let (lo, hi) = self.piece(piece); + let whole = from <= lo && hi <= to; + let (lo, hi) = (lo.max(from), hi.min(to)); + // SAFETY: as below; `hi <= total`. + unsafe { + std::ptr::copy_nonoverlapping(self.data.add(lo), snapshot.as_mut_ptr().add(lo), hi - lo); + } + kept.0[piece] = whole; + } + } + return; + } + if wide_back() { + // Noted, and taken with the submission's other snapshots when + // its refreshes are done (`take_snapshots`): the range is + // declared from here on, so nothing changes its bytes before + // then. The snapshot's memory stays where it is until the + // range is done with (`copy_back_done`). + let mut snaps = SNAPS.lock().unwrap_or_else(|e| e.into_inner()); + let (data, snapshot) = (self.data as usize, snapshot.as_mut_ptr() as usize); + snaps.extend(parts.into_iter().filter(|&(from, to)| from < to).map(|(from, to)| (data + from, snapshot + from, to - from))); + return; + } + for (from, to) in parts { + if from < to { + // SAFETY: the copy's mapping and the snapshot's allocation + // (`pooled`) both hold `total` bytes, and `to <= total`. + unsafe { + copy_wide(self.data.add(from), snapshot.as_mut_ptr().add(from), to - from); + } + } + } + } + + /// After the submission ran: copies the bytes its shaders wrote back + /// into title memory (unmapped pages left alone), and only those: the + /// title's threads write the same buffers while the GPU runs (its + /// command memory shares the big GPU heap with what shaders write), and + /// putting back the copy's older bytes there broke the title's own + /// records (a fence list read as -1, title+0x4e9b54a). Returns the bytes + /// written. The range must lie in ranges declared with + /// [`Shadow::writing`] and not yet done: `Host::execute` passes the + /// union of a submission's ranges, each byte once, then calls + /// [`Shadow::copy_back_done`]. + pub(crate) fn copy_back(&self, address: usize, len: usize) -> usize { + self.copy_back_with(address, len, None) + } + + /// [`Shadow::copy_back`]; `found`, if given, is the pieces of the range + /// that differ from the snapshot, found beforehand ([`find_all`]). + pub(crate) fn copy_back_with(&self, address: usize, len: usize, found: Option>) -> usize { + if self.place.is_some() { + return 0; + } + let snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let mut written = 0; + let (from, to) = self.inside(address, len); + let start = self.start as usize; + self.compared(from, to); + if let Some(before) = &*snapshot + && from < to + { + // SAFETY: `writing` set the snapshot's bytes of every declared + // range, at the copy's offsets. + let before = unsafe { std::slice::from_raw_parts(before.as_ptr().add(from), to - from) }; + // By 64 KiB piece: the copy compared with its bytes before the + // submission (on several threads: gigabytes a frame, bound by + // memory speed), title memory read only where the GPU wrote. + #[cfg(feature = "diagnostics")] + let scanning = std::time::Instant::now(); + let differing = match found { + Some(found) => found, + None => self.differing(from, to, before), + }; + #[cfg(feature = "diagnostics")] + let syncing = { + use crate::copystat::{C, add}; + add(C::BackScanUs, scanning.elapsed().as_micros() as u64); + add(C::BackDiffer, differing.len() as u64); + std::time::Instant::now() + }; + // Where the copy changes (the GPU wrote, and below the title's + // bytes come in), a kept snapshot is no longer current. + for &(at, n) in &differing { + self.changed(at, at + n); + } + let mut title = vec![0u8; PIECE]; + for (at, n) in differing { + // SAFETY: inside the mapping; only the submitting thread + // writes it. + let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; + let old = &before[at - from..at - from + n]; + // From the first byte that differs to the last: title + // memory is read and written there only (a shader that sets + // a few words of a piece cost a read, a walk and a write of + // all 64 KiB of it). + let Some(first) = first_difference(host, old) else { + continue; + }; + let last = last_difference(host, old).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (host, old) = (&mut host[first..=last], &old[first..=last]); + let title = &mut title[..n]; + if !crate::host::read_into((start + at) as *const u8, title) { + continue; + } + // Title memory with the GPU's bytes put in; the copy takes + // the title's bytes in turn. + // Without a branch, so the loop runs many bytes at a time: + // the GPU's byte where the copy's byte is not what it was + // before the submission, else the title's. (With the two + // searches above this was 44 ms a frame for 970 pieces.) + let mut differs = 0u8; + for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) { + let gpu = if *h != *o { 0xffu8 } else { 0 }; + let merged = (*t & !gpu) | (*h & gpu); + differs |= merged ^ *t; + *t = merged; + *h = merged; + } + if differs != 0 { + crate::watch::writing(start + at, n); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + written += n; + } + } + // Our write shows as a title write at the copy's next refresh, + // which copies those pages once more (some dozens of MB a + // frame). Asking about the whole range here, to note them + // current, cost more: 19-31 askings a frame over 110-174 MB of + // view memory, each a walk of its guards. + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackSyncUs, syncing.elapsed().as_micros() as u64); + } + written + } + + /// Offsets `[from, to)` of the copy are compared with the snapshot: for + /// the frame line's counts. + fn compared(&self, from: usize, to: usize) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackCompared, (to - from) as u64); + let (bytes, ranges) = if self.window { (2, 5) } else { (3, 6) }; + BACK_CLASS[bytes].fetch_add((to - from) as u64, Ordering::Relaxed); + BACK_CLASS[ranges].fetch_add(1, Ordering::Relaxed); + if !self.window && self.len >= 1 << 20 { + BACK_CLASS[4].fetch_add((to - from) as u64, Ordering::Relaxed); + } + } + + /// [`relay`]: the declared range `[address, address + len)` of a copy + /// in the PC's memory is about to be looked through + /// (`crate::shadow::find_all`) by the thread that settles: counted as + /// [`Shadow::copy_back_with`] counts it. + pub(crate) fn relay_compared(&self, address: usize, len: usize) { + let (from, to) = self.inside(address, len); + self.compared(from, to); + } + + /// [`relay`], for a copy in the PC's memory: offsets `[at, at + n)` + /// are a 64 KiB piece of a declared range that differed from the + /// snapshot when it was looked through. What the card wrote there + /// since the snapshot was last brought up goes into title memory, from + /// the first to the last such byte, and into the snapshot, so that the + /// next flight's merge finds only what the card writes from now on. + /// The copy is read once and never written: a later flight's shaders + /// may be writing it at this moment. Under the snapshot's lock, which + /// [`Shadow::merge_under_writes`] holds while it reads title memory + /// and puts the title's bytes into the copy and the snapshot: the two + /// never see each other half done. `now` and `title` are scratch + /// memory. Returns the bytes written to title memory. + pub(crate) fn relay_merge(&self, at: usize, n: usize, now: &mut Vec, title: &mut Vec) -> usize { + let start = self.start as usize; + if self.card.is_some() || n == 0 || at + n > self.len as usize { + return 0; + } + let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let Some(before) = snapshot.as_mut() else { + return 0; + }; + now.clear(); + now.reserve(n); + // SAFETY: inside the copy's mapping (checked above), read into + // room just reserved; the card may write the mapping meanwhile, and + // each byte read is one it held at some moment. + unsafe { + std::ptr::copy_nonoverlapping(self.data.add(at), now.as_mut_ptr(), n); + now.set_len(n); + } + // SAFETY: the snapshot's allocation holds the copy's length + // (`writing`), and these offsets are in a range declared and not + // done with, whose bytes it holds; nothing else touches them + // without the lock held here. + let held = unsafe { std::slice::from_raw_parts_mut(before.as_mut_ptr().add(at), n) }; + let Some(first) = first_difference(now, held) else { + return 0; + }; + let last = last_difference(now, held).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (now, held) = (&now[first..=last], &mut held[first..=last]); + title.clear(); + title.resize(n, 0); + // Title memory not there: looked at again when the next flight + // that declared the range lands (the snapshot stays as it is). + if !crate::host::read_into((start + at) as *const u8, title) { + return 0; + } + if !merge_piece(now, held, title) { + return 0; + } + crate::watch::writing(start + at, n); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + n + } + + /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory) of + /// `[from, to)` of the copy that differ from `before` (the bytes from + /// `from` on), as (offset, bytes) in order; compared on several threads + /// when the range is big. + fn differing(&self, from: usize, to: usize, before: &[u8]) -> Vec<(usize, usize)> { + let (start, data) = (self.start as usize, self.data as usize); + let scan = |a: usize, b: usize| -> Vec<(usize, usize)> { + let mut found = Vec::new(); + let mut at = a; + while at < b { + let n = (PIECE - (start + at) % PIECE).min(b - at); + // SAFETY: inside the mapping, which nothing writes while a + // submission's results are compared. + let host = unsafe { std::slice::from_raw_parts((data + at) as *const u8, n) }; + if host != &before[at - from..at - from + n] { + found.push((at, n)); + } + at += n; + } + found + }; + const PER_THREAD: usize = 16 << 20; + let threads = ((to - from) / PER_THREAD).clamp(1, 8); + if threads == 1 { + return scan(from, to); + } + // Cut on piece boundaries, so that every thread sees whole pieces. + let cut = |i: usize| { + if i == threads { + return to; + } + let at = from + (to - from) / threads * i; + (at - (start + at) % PIECE).max(from) + }; + let scan = &scan; + std::thread::scope(|s| { + let parts: Vec<_> = (0..threads) + .map(|i| { + let (a, b) = (cut(i), cut(i + 1)); + s.spawn(move || scan(a, b)) + }) + .collect(); + parts + .into_iter() + .flat_map(|part| match part.join() { + Ok(found) => found, + Err(panic) => std::panic::resume_unwind(panic), + }) + .collect() + }) + } + + /// After [`Shadow::copy_back`] of a submission's ranges: every submitted + /// step that declared one of `ranges` (`(address, end)`, as declared) is + /// done with it (one submission runs at a time), and the snapshot with + /// the last range. + /// + /// With [`relay`] several submissions may hold a range: `ranges` are + /// those of one of them (each once), and a range is done with when the + /// last submission that declared it is ([`Flights`]). + pub(crate) fn copy_back_done(&self, ranges: &[(usize, usize)]) { + if self.place.is_some() { + return; + } + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + if relay() { + let free = self.flights.lock().unwrap_or_else(|e| e.into_inner()).done(ranges); + pending.retain(|r| !free.contains(r)); + } else { + pending.retain(|r| !ranges.contains(r)); + } + if !pending.is_empty() || self.card.is_some() { + return; + } + if keeps() { + // Kept for the next submission, if it is worth it (a megabyte + // or more) and there is room. + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if !kept.1 && self.len >= 1 << 20 { + if KEPT_BYTES.fetch_add(self.len, Ordering::Relaxed) + self.len <= kept_most() { + kept.1 = true; + } else { + KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed); + } + } + if kept.1 { + return; + } + // Given back: nothing of it is current next time. (The lock + // on the pieces ends here: `copy_back` takes it while it holds + // the snapshot's.) + kept.0.clear(); + } + if let Some(bytes) = self.before.lock().unwrap_or_else(|e| e.into_inner()).take() { + give_back(bytes); } } - /// `[address, address + len)` cut to the buffer, as offsets in the copy. - fn inside(&self, address: usize, len: usize) -> (usize, usize) { - let (start, end) = (self.start as usize, (self.start + self.len) as usize); - let from = address.clamp(start, end); - (from - start, (address + len).clamp(from, end) - start) + /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory, as + /// [`Shadow::differing`] cuts them) that hold offsets `[from, to)` of + /// the copy; `from < to`. + fn pieces(&self, from: usize, to: usize) -> std::ops::Range { + pieces_of(self.start as usize, from, to) } - /// Shaders of `list` may write `[address, address + len)` of the copy - /// (unordered access): after the list's submission has run, the range - /// is copied back into title memory, where the title reads it; until - /// then no refresh copies title memory over it. Call after the - /// [`Shadow::refresh`] that gives the shaders the title's data. - /// - /// shortcut: what shaders wrote is found by keeping the range's bytes - /// before the submission (a copy per declared range and submission); - /// a GPU-side dirty mask would save that if big ranges make it slow. - pub(crate) fn gpu_writes(self: &Arc, list: &HostList, address: u64, len: u64) { - let len = len.min(self.left(address)); - list.defer_gpu_write(self, address as usize, len as usize); + /// The offsets in the copy that piece `piece` holds. + fn piece(&self, piece: usize) -> (usize, usize) { + piece_at(self.start as usize, self.len as usize, piece) } - /// At submission, after the range's refresh: a submitted list's shaders - /// write this range. Its bytes are kept to tell later what the GPU wrote: - /// one snapshot per copy and submission, grown to cover every range the - /// submission declares (the world declares overlapping views of its - /// 174 MB heap dozens of times), in reused memory (fresh snapshots cost - /// ~2.3 million page faults per world frame). - pub(crate) fn writing(&self, address: usize, len: usize) { - self.pending + /// The copy's bytes at offsets `[from, to)` change: a kept snapshot is + /// not current there any more. + fn changed(&self, from: usize, to: usize) { + if !keeps() || from >= to { + return; + } + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if kept.0.is_empty() { + return; + } + for piece in self.pieces(from, to) { + kept.0[piece] = false; + } + } + + /// Whether shaders of a submission not yet copied back may be writing + /// the copy. + pub(crate) fn writes_pending(&self) -> bool { + !self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } + + /// Whether [`Shadow::update`] of `[address, address + len)` would leave + /// title bytes behind: a range shaders may be writing holds a page the + /// title wrote since the copy last took it. The answer comes from the + /// write-watch journal alone, as the submission's one asking left it + /// (`crate::watch::asked`); where the journal cannot say (memory not + /// write-watched, a range not asked about) it is yes. A page the copy + /// never took whole counts as written if the title ever wrote it. + /// + /// For submissions sent to the card without a wait + /// (`crate::host::late`): the ranges are those of flights in the air, + /// which are then settled before this refresh. + pub(crate) fn stale_under_writes(&self, address: usize, len: usize) -> bool { + 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 { + return false; + } + let busy: Vec<(usize, usize)> = self + .pending .lock() .unwrap_or_else(|e| e.into_inner()) - .push((address, address + len)); - let (from, to) = self.inside(address, len); - // SAFETY: inside the mapping. - let host = - |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) }; - let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); - let (start, end) = match &*before { - Some((at, bytes)) => ((*at).min(from), (at + bytes.len()).max(to)), - None => (from, to), - }; - if let Some((at, bytes)) = &*before - && (*at, at + bytes.len()) == (start, end) - { - return; + .iter() + .filter(|&&(a, e)| a < to && e > from) + .map(|&(a, e)| (a.max(from), e.min(to))) + .collect(); + if busy.is_empty() { + return false; } - // Parts newly covered from the copy, the rest as it was taken. - let mut grown = pooled(end - start); - match before.take() { - Some((at, bytes)) => { - grown.extend_from_slice(host(start, at)); - grown.extend_from_slice(&bytes); - grown.extend_from_slice(host(at + bytes.len(), end)); - give_back(bytes); - } - None => grown.extend_from_slice(host(start, end)), + if self.watched.load(Ordering::Relaxed) == NOT_WATCHED { + return true; } - *before = Some((start, grown)); + let base = start / PAGE; + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) { + Some((_, written)) => written.into_iter().any(|(page, write)| { + page >= base && copied.get(page - base).is_none_or(|&at| at == 0 || write > at) + }), + None => true, + }) } - /// After the submission ran: copies the bytes its shaders wrote back - /// into title memory (unmapped pages left alone), and only those: the - /// title's threads write the same buffers while the GPU runs (its - /// command memory shares the big GPU heap with what shaders write), and - /// putting back the copy's older bytes there broke the title's own - /// records (a fence list read as -1, title+0x4e9b54a). Returns the bytes - /// written. - pub(crate) fn copy_back(&self, address: usize, len: usize) -> usize { - let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); - let mut written = 0; - let (from, to) = self.inside(address, len); - let start = self.start as usize; - if let Some((taken, before)) = &*snapshot - && *taken <= from - && to <= taken + before.len() - && from < to - { - let before = &before[from - taken..to - taken]; - // By 64 KiB piece: the copy compared with its bytes before the - // submission, title memory read only where the GPU wrote. - const PIECE: usize = 64 << 10; - let mut title = vec![0u8; PIECE]; - let mut synced = Vec::new(); - let mut at = from; - while at < to { - let n = (PIECE - (start + at) % PIECE).min(to - at); - // SAFETY: inside the mapping; only the submitting thread - // writes it. - let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; - let old = &before[at - from..at - from + n]; + /// Where [`Shadow::stale_under_writes`] says yes: puts the bytes the + /// title changed into the copy, in the ranges shaders may be writing, + /// and only those bytes, so that what the shaders write beside them + /// stays (`crate::host::late_exact`). For each page of such a range + /// that the title wrote since the copy last took it, title memory as + /// it is now is compared with what the copy held when the range was + /// given to the shaders: the copy's CPU side for a copy in the card's + /// memory (the changed runs go up before the next submission, each a + /// copy of its own bytes, `runs_left` of them at most), the snapshot + /// for the others (the changed bytes go into the copy and into the + /// snapshot, so the compare after the card ran takes them for the + /// title's and not the shaders'). + /// + /// Whether the caller must still settle the flights: the journal + /// cannot say what was written, a snapshot is missing, or `runs_left` + /// ran out. Pages done before that stay done. + pub(crate) fn merge_under_writes(&self, address: usize, len: usize, runs_left: &mut usize) -> bool { + 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 { + return false; + } + let busy: Vec<(usize, usize)> = self + .pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter(|&&(a, e)| a < to && e > from) + .map(|&(a, e)| (a.max(from), e.min(to))) + .collect(); + if busy.is_empty() { + return false; + } + if self.watched.load(Ordering::Relaxed) == NOT_WATCHED { + return true; + } + let base = start / PAGE; + let mut title = vec![0u8; PAGE]; + for (a, e) in busy { + // As the refresh itself asks (`update_free`): the journal if + // the submission's asking covered the range, else the kernel, + // else the guards. The journal alone said nothing for copies + // of view memory, which is guarded and not write-watched, and + // those were all of run 99's cases: the flights were settled + // 4-5 times a frame for "0 pages looked at". + let Some((now, written)) = crate::watch::writes(a, e, true) else { + return true; + }; + let stale: Vec = { + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + written + .into_iter() + .filter(|&(page, write)| page >= base && copied.get(page - base).is_none_or(|&at| at == 0 || write > at)) + .map(|(page, _)| page) + .collect() + }; + for page in stale { + let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e)); + if lo >= hi { + continue; + } + let n = hi - lo; let title = &mut title[..n]; - if host != old && crate::host::read_into((start + at) as *const u8, title) { - // Title memory with the GPU's bytes put in; the copy - // takes the title's bytes in turn. - let mut runs: Vec<(usize, usize)> = Vec::new(); - let mut run = None; - for (i, ((t, h), o)) in - title.iter_mut().zip(host.iter_mut()).zip(old).enumerate() - { - if *h != *o && *t != *h { - *t = *h; - run.get_or_insert(i); - } else if let Some(first) = run.take() { - runs.push((first, i - first)); - } - *h = *t; + // The lock of the copy's reference (the snapshot, or the + // CPU's side of a copy in the card's memory), from before + // title memory is read until the title's bytes are in: with + // the copy-back on its own thread ([`relay`]) that thread + // puts what the card wrote into title memory and into the + // reference under the same lock, and a page read before + // such a merge and compared after it would take the card's + // bytes for the title's. + let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); + // A page that is not there is left as it is, and looked at + // again next time. + if !crate::host::read_into(lo as *const u8, title) { + continue; + } + MERGED[0].fetch_add(1, Ordering::Relaxed); + let at = lo - start; + if self.card.is_some() { + // SAFETY: inside the mapping of the copy's CPU side, + // which only the submitting thread writes. + let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; + let runs = changed_runs(title, held); + if runs.len() > *runs_left { + return true; } - if let Some(first) = run.take() { - runs.push((first, n - first)); + *runs_left -= runs.len(); + for (r, m) in runs { + held[r..r + m].copy_from_slice(&title[r..r + m]); + self.card_changed(at + r, at + r + m); + MERGED[1].fetch_add(1, Ordering::Relaxed); + MERGED[2].fetch_add(m as u64, Ordering::Relaxed); } - if !runs.is_empty() { - crate::watch::writing(start + at, n); - for &(off, len) in &runs { - crate::host::write_mapped( - (start + at + off) as *mut u8, - title[off..off + len].as_ptr(), - len, - ); - } - written += runs.iter().map(|&(_, len)| len).sum::(); + } else { + let Some(snapshot) = before.as_mut() else { + return true; + }; + // SAFETY: the snapshot's allocation holds the copy's + // bytes at the copy's offsets (`writing`), and these + // are in a declared range. + let held = unsafe { std::slice::from_raw_parts_mut(snapshot.as_mut_ptr().add(at), n) }; + for (r, m) in changed_runs(title, held) { + // SAFETY: inside the copy's mapping. The card may be + // writing the copy beside these bytes; they are + // written here and nothing around them. + unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) }; + held[r..r + m].copy_from_slice(&title[r..r + m]); + MERGED[1].fetch_add(1, Ordering::Relaxed); + MERGED[2].fetch_add(m as u64, Ordering::Relaxed); } - synced.push((start + at) / PAGE); } - at += n; - } - // Pages made equal to title memory are current in the copy, so - // our own write is not taken for the title's; others keep what - // they had (a title write there shows at the next refresh). - let (first, last) = ((start + from).div_ceil(PAGE), (start + to) / PAGE); - if first < last - && !synced.is_empty() - && self.watched.load(Ordering::Relaxed) != NOT_WATCHED - && let Some((now, _)) = crate::watch::writes(first * PAGE, last * PAGE, true) - { - let base = start / PAGE; - let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - for page in synced.into_iter().filter(|p| (first..last).contains(p)) { - copied[page - base] = now; + drop(before); + // Taken, if the range holds all of the page that is in the + // copy; else the rest of it is the refresh's, which notes + // only whole pages, and the page is looked at again. + if (page * PAGE).max(start) >= a && ((page + 1) * PAGE).min(end) <= e { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(at) = copied.get_mut(page - base) { + *at = now; + } } } } - // Every submitted step that declared the range is done with it (one - // submission runs at a time), and the snapshot with the last range. - let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); - pending.retain(|&r| r != (address, address + len)); - if pending.is_empty() - && let Some((_, bytes)) = snapshot.take() - { - give_back(bytes); - } - written + false } /// 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 { + // In place: the card reads title memory itself. + if self.place.is_some() { + 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 { @@ -326,6 +2403,7 @@ impl Shadow { if let Some((now, written)) = crate::watch::writes(from, to, true) { self.watched.store(1, Ordering::Relaxed); let copied = self.copy_stale(from, to, now, &written); + self.refresh_check(from, to); #[cfg(feature = "diagnostics")] { use crate::copystat::{C, add}; @@ -336,10 +2414,73 @@ impl Shadow { } self.watched.store(NOT_WATCHED, Ordering::Relaxed); } - self.copy_queued(from, to); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::WholeBytes, (to - from) as u64); + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + self.copy(from, to); + #[cfg(feature = "diagnostics")] + crate::copystat::whole(from, to - from, started.elapsed().as_micros() as u64); to - from } + /// Diagnostic (`VICTORY_REFRESH_CHECK=1`; off by default): after a + /// refresh of `[from, to)` that trusted the write watch or the guards, + /// the first 256 bytes of every 64 KiB block of it are read from title + /// memory and compared with the copy. A block that differs on three + /// refreshes in a row was changed with nothing to tell of it (a write + /// through another view of its pages, as DirectStorage's page + /// destinations make) and the card reads old bytes there: said with + /// the copy and the address. One that differs once is a write of the + /// title's that arrived between the refresh and the look. + fn refresh_check(&self, from: usize, to: usize) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1") || crate::host::walls_trace()) { + return; + } + const SAMPLE: usize = 256; + // Blocks found differing: how many refreshes in a row. + static DIFFERING: Mutex>> = Mutex::new(None); + static SAID: AtomicU64 = AtomicU64::new(0); + let start = self.start as usize; + let mut title = [0u8; SAMPLE]; + let mut at = from; + while at < to { + let n = SAMPLE.min(to - at); + if crate::host::read_into(at as *const u8, &mut title[..n]) { + // SAFETY: `[from, to)` lies inside the buffer (`update`), + // so these bytes are inside the copy's mapping. + let copy = unsafe { std::slice::from_raw_parts(self.data.add(at - start).cast_const(), n) }; + let mut map = DIFFERING.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(Default::default); + if copy == &title[..n] { + map.remove(&at); + } else { + let times = map.entry(at).or_insert(0); + *times += 1; + if *times == 3 { + let said = SAID.fetch_add(1, Ordering::Relaxed) + 1; + if said <= 64 || said.is_power_of_two() { + tracing::warn!( + said, + copy = self.id, + copy_start = format_args!("{start:#x}"), + copy_bytes = self.len, + address = format_args!("{at:#x}"), + refreshed = format_args!("{from:#x}..{to:#x}"), + on_the_card = self.card.is_some(), + window = self.window, + "a host copy of title memory is stale after its refresh, three times in a row: the memory changed with nothing to tell of it (VICTORY_REFRESH_CHECK=1)" + ); + } + } + } + } + // The first bytes of the next 64 KiB block. + at = (at / PAGE + 1) * PAGE; + } + } + /// Copies the pages of `[from, to)` written after their last copy /// (`written`: last writes by page, in page order; `now`: this /// asking), whole pages within the buffer. @@ -367,26 +2508,250 @@ impl Shadow { } run.get_or_insert(page); } else if let Some(first) = run.take() { - bytes += self.copy_queued((first * PAGE).max(from), (page * PAGE).min(to)); + bytes += self.copy((first * PAGE).max(from), (page * PAGE).min(to)); } } // Cut to the range: next to it shaders may be writing the copy. if let Some(first) = run { - bytes += self.copy_queued((first * PAGE).max(from), ((last + 1) * PAGE).min(to)); + bytes += self.copy((first * PAGE).max(from), ((last + 1) * PAGE).min(to)); } bytes } - /// Copies title memory into the copy, queued where the caller collects a - /// submission's refreshes; outside that collection the copy is made at once. - fn copy_queued(&self, from: usize, to: usize) -> usize { + /// Copies title memory `[from, to)`, cut to the buffer, into the copy. + fn copy(&self, from: usize, to: usize) -> usize { let (start, end) = (self.start as usize, (self.start + self.len) as usize); let (from, to) = (from.max(start), to.min(end)); // SAFETY: inside the mapping (`from` and `to` are within the buffer). let at = unsafe { self.data.add(from - start) }; - crate::copy_pool::copy(at, from as *const u8, to - from); + crate::host::copy_mapped(at, from as *const u8, to - from, false); + // After the bytes are in: a snapshot taken meanwhile is not current. + self.changed(from - start, to - start); + self.card_changed(from - start, to - start); to - from } + + /// Whether shaders read and write this copy in the card's own memory + /// ([`cards`]). + pub(crate) fn carded(&self) -> bool { + self.card.is_some() + } + + /// The CPU side's bytes at offsets `[from, to)` changed: they go to the + /// card's side before the next submission. + fn card_changed(&self, from: usize, to: usize) { + let Some(card) = &self.card else { + return; + }; + if from >= to { + return; + } + let mut dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); + match dirty.last_mut() { + Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)), + _ => dirty.push((from, to)), + } + } + + /// Of a copy in the card's memory: the CPU's side (PC memory), the + /// card side's bytes from before if made yet, and their size. + pub(crate) fn card_sides(&self) -> Option<(&ID3D12Resource, Option, u64)> { + let card = self.card.as_ref()?; + let before = card.before.lock().unwrap_or_else(|e| e.into_inner()).clone(); + Some((&card.staging, before, card.size)) + } + + /// Shader writes are declared for a copy in the card's memory: makes + /// its "before" twin with `make` (bytes to buffer) if it has none. + /// Whether one was made now: the caller fills it, whole, from the + /// card's side before the submission's lists run. Without one (no + /// memory) every piece of a declared range is fetched. + pub(crate) fn card_make_before(&self, make: impl FnOnce(u64) -> Option) -> bool { + let Some(card) = &self.card else { + return false; + }; + let mut before = card.before.lock().unwrap_or_else(|e| e.into_inner()); + if before.is_some() { + return false; + } + *before = make(card.size); + if before.is_some() { + CARD_BYTES[1].fetch_add(card_hash_bytes(card.size), Ordering::Relaxed); + } + before.is_some() + } + + /// The declared range `[address, end)` as the compare on the card + /// takes it; `None` if none of it lies in the copy. + pub(crate) fn card_span(&self, address: usize, end: usize) -> Option { + let (from, to) = self.inside(address, end.saturating_sub(address)); + (from < to).then(|| card_span_of(self.start as usize, from, to)) + } + + /// The pieces that hold offsets `[from, to)` of the copy (cut to it), + /// as the card's hashing takes them. + pub(crate) fn card_run(&self, from: usize, to: usize) -> CardSpan { + let to = to.min(self.len as usize); + card_span_of(self.start as usize, from.min(to.saturating_sub(1)), to) + } + + /// The offsets of piece `i` of `span` that lie in the span. + pub(crate) fn card_piece(&self, span: &CardSpan, i: u32) -> (usize, usize) { + card_piece_of(self.start as usize, self.len as usize, span, i) + } + + /// The walls trace (`crate::host::walls_trace`): a piece of `fetched` + /// bytes of this copy came back from the card and `written` of them + /// went into title memory. Summed per buffer and logged once a frame: + /// which shader-written buffers the title's CPU could see fresh in + /// that frame, and how much of each changed. + pub(crate) fn walls_merged(&self, fetched: usize, written: usize) { + if !crate::host::walls_trace() { + return; + } + static SEEN: Mutex<(u64, BTreeMap)> = Mutex::new((0, BTreeMap::new())); + let frame = crate::frame::current(); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if seen.0 != frame { + let buffers: Vec = seen + .1 + .iter() + .map(|(at, v)| format!("{at:#x}+{:#x}: {} pieces, {} fetched, {} written", v.0, v.1, v.2, v.3)) + .take(32) + .collect(); + if !buffers.is_empty() { + tracing::info!( + frame = seen.0, + count = seen.1.len(), + buffers = ?buffers, + "walls trace: shader-written card buffers merged into title memory in this frame" + ); + } + seen.1.clear(); + seen.0 = frame; + } + let entry = seen.1.entry(self.start).or_insert((self.len, 0, 0, 0)); + entry.1 += 1; + entry.2 += fetched as u64; + entry.3 += written as u64; + } + + /// After a submission, for a copy in the card's memory: `gpu` is what + /// the card's side holds at offset `at` on, in a piece the compare + /// found differing. The bytes shaders wrote (those that differ from the + /// CPU's side, which is what the card's side held when they started) + /// go into title memory, from the first to the last of them, as + /// [`Shadow::copy_back`] puts them; the CPU's side takes the result and + /// sends it up before the next submission. `title` is scratch memory. + /// Returns the bytes written to title memory. + pub(crate) fn card_merge(&self, at: usize, gpu: &[u8], title: &mut Vec) -> usize { + let start = self.start as usize; + if self.card.is_none() || at + gpu.len() > self.len as usize { + return 0; + } + // SAFETY: inside the mapping (checked above); only the submitting + // thread writes it. + let old = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) }; + let Some(first) = first_difference(gpu, old) else { + return 0; + }; + let last = last_difference(gpu, old).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (gpu, old) = (&gpu[first..=last], &mut old[first..=last]); + title.clear(); + title.resize(n, 0); + let mut written = 0; + if crate::host::read_into((start + at) as *const u8, title) { + // As in `copy_back`: the card's byte where it is not what it + // was before the submission, else the title's. + let mut differs = 0u8; + for ((t, g), o) in title.iter_mut().zip(gpu).zip(old.iter_mut()) { + let wrote = if *g != *o { 0xffu8 } else { 0 }; + let merged = (*t & !wrote) | (*g & wrote); + differs |= merged ^ *t; + *t = merged; + *o = merged; + } + if differs != 0 { + crate::watch::writing(start + at, n); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + written = n; + } + } else { + // Title memory is not mapped there: the copy keeps what the + // card wrote, as before. + old.copy_from_slice(gpu); + } + // The card's side and its "before" take the result. + self.card_changed(at, at + n); + written + } + + /// [`relay`], for a copy in the card's memory: `gpu` is what the + /// card's side held at offset `at` on when a fetch sent after send + /// `fetched_after` (`crate::host`'s order of the queue) ran, in a piece + /// the compare found differing. The bytes that differ from the CPU's + /// side are what shaders wrote; they go into title memory, from the + /// first to the last of them, and into the CPU's side. Nothing is sent + /// up afterwards (the card holds these bytes or newer ones: sending + /// them up could undo a later flight's write), and the title's other + /// bytes are left to the refresh. + /// + /// Left out: bytes of the CPU's side that hold title bytes the card + /// had not received when the fetch ran, those still to go up and those + /// that went up with a later send. There the card's side is the older + /// one, and taking it for a shader's write would put it over what the + /// title wrote. Under the CPU side's lock (the snapshot's, which such + /// a copy has no other use for), as [`Shadow::merge_under_writes`]. + /// `title` is scratch memory. Returns the bytes written to title + /// memory. + pub(crate) fn card_merge_relay(&self, at: usize, gpu: &[u8], fetched_after: u64, title: &mut Vec) -> usize { + let start = self.start as usize; + let Some(card) = &self.card else { + return 0; + }; + if at + gpu.len() > self.len as usize { + return 0; + } + let _side = self.before.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: inside the mapping (checked above). The offsets are in a + // range declared and not done with, which no refresh writes; what + // does write it (the title's bytes put in under shader writes) + // holds the lock held here. + let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) }; + let Some(first) = first_difference(gpu, held) else { + return 0; + }; + let last = last_difference(gpu, held).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (gpu, held) = (&gpu[first..=last], &mut held[first..=last]); + let skip: Vec<(usize, usize)> = { + let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); + let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner()); + dirty + .iter() + .copied() + .chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1))) + .filter(|&(a, b)| a < at + n && b > at) + .collect() + }; + title.clear(); + title.resize(n, 0); + let mapped = crate::host::read_into((start + at) as *const u8, title); + let mut changed = false; + for (a, b) in outside(at, at + n, skip) { + let (a, b) = (a - at, b - at); + // Title memory that is not mapped: the CPU's side keeps what + // the card wrote, as before; `title` is scratch then. + changed |= merge_piece(&gpu[a..b], &mut held[a..b], &mut title[a..b]); + } + if !mapped || !changed { + return 0; + } + crate::watch::writing(start + at, n); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + n + } } struct Entry { @@ -417,9 +2782,93 @@ pub(crate) fn unregister(resource: usize, start: u64) { buffers().remove(&(start, resource)); } +/// The title buffer holding `address`, as (start, length), without making +/// its copy (diagnostics: which buffer a dropped program's root view names). +#[cfg(feature = "diagnostics")] +pub(crate) fn extent(address: u64) -> Option<(u64, u64)> { + buffers() + .range(..=(address, usize::MAX)) + .rev() + .take(64) + .find(|(_, e)| e.end > address) + .map(|(k, e)| (k.0, e.end - k.0)) +} + +/// Title memory `[at, at + len)` is about to show something else or be +/// given up: what is in place there (`crate::inplace`) is taken out of the +/// tables, so that the next ask makes a copy or opens the memory anew, and +/// goes when no list and no slot holds it any more. Returns how many. +pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 { + let end = at.saturating_add(len); + let mut gone: Vec> = Vec::new(); + { + let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let keys: Vec<(u64, u64)> = map + .range((at.saturating_sub(WINDOW), 0)..(end, 0)) + .filter(|(key, shadow)| shadow.place.is_some() && key.0 + key.1 > at) + .map(|(key, _)| *key) + .collect(); + gone.extend(keys.into_iter().filter_map(|key| map.remove(&key))); + } + { + // As `lookup` finds a buffer: among the 256 that start below. + let mut map = buffers(); + for (_, entry) in map.range_mut(..(end, 0)).rev().take(256) { + if entry.end > at && entry.shadow.as_ref().is_some_and(|s| s.place.is_some()) { + gone.extend(entry.shadow.take()); + } + } + } + let n = gone.len() as u64; + for shadow in gone { + crate::host::retire(shadow); + } + n +} + +/// For the in-place census (`crate::inplace`): the title buffers (start, +/// bytes, false) and the windows outside buffers that have a copy (start, +/// bytes, true). +pub(crate) fn spans() -> Vec<(u64, u64, bool)> { + let mut spans: Vec<(u64, u64, bool)> = buffers().iter().map(|(key, entry)| (key.0, entry.end - key.0, false)).collect(); + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + spans.extend(loose.keys().map(|&(start, len)| (start, len, true))); + spans +} + /// The copy of the innermost title buffer holding `[address, address + -/// len)`, made on first use. +/// len)`, made on first use. A `len` of 0 or 1 is an ask without a length +/// (a root view: the caller reads on to the copy's end). pub(crate) fn find(address: u64, len: u64) -> Option> { + lookup(address, len, false) +} + +/// As [`find`], for an ask that is done with the copy when its list has +/// run (a draw's vertex and index buffers, indirect arguments): outside +/// buffer objects it takes a window that is there already and holds the +/// range ([`holder`]), and makes one of its own only if none does. +/// +/// [`find`] names a window by the ask alone, which a descriptor slot needs +/// (the slot shows the window its view found when it was made, and the +/// pass that brings it up to date must find the same one). A draw needs no +/// such thing: it binds the copy it found and brings that copy up to date. +/// Named by the ask alone, every draw's range was a window of its own +/// wherever the windows are cut finer than 4 MiB: draws that bind +/// different ranges of the same memory then each copied their range, and +/// windows nothing asked for again for ten seconds were let go and made +/// (and copied) anew. Run 71, on a 256 KiB grid: 350 MB copied per frame +/// against 120 MB, 7,087 write-watch askings against 2,600, and 5,263 +/// windows (4.5 GB) let go in two minutes against 393 in a whole run. +pub(crate) fn find_any(address: u64, len: u64) -> Option> { + // With whole windows (the default) there is one window to a cell and + // nothing to choose: exactly `find`. + if !fine() { + return find(address, len); + } + lookup(address, len, true) +} + +fn lookup(address: u64, len: u64, any: bool) -> Option> { let end = address.checked_add(len.max(1))?; let mut map = buffers(); let key = map @@ -430,29 +2879,53 @@ pub(crate) fn find(address: u64, len: u64) -> Option> { .map(|(k, _)| *k); let Some(key) = key else { drop(map); - return loose(address, end); + return loose(address, end, len <= 1, any); }; let entry = map.get_mut(&key)?; if entry.shadow.is_none() { let len = entry.end - key.0; // Rounded up so that views ending in the buffer's last 256 bytes fit. // Shaders write some buffers (unordered access), so not upload memory. - let host = host()?; - let Some((buffer, data)) = host.shared_buffer(len.next_multiple_of(1 << 16)) else { - tracing::warn!( - address = format_args!("{:#x}", key.0), - len, - "could not allocate host copy for title buffer" - ); - return None; - }; + let size = len.next_multiple_of(1 << 16); + // In place, if asked for and the memory can be opened + // (`crate::inplace::place_for`): the buffer is the title's own + // memory. Not the big ones `cards` puts in the card's memory: those + // are read too often to stay in the PC's. + let big = cards() && size >= card_limits().0; + if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) { + entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); + return entry.shadow.clone(); + } + let (buffer, data) = host()?.shared_buffer(size)?; crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0)); + // A big one, with `cards`: shaders get a buffer in the card's own + // memory, and the one just made is the CPU's side. + let (buffer, card) = match card_for(size) { + Some(on_card) => { + crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", key.0)); + tracing::info!( + start = format_args!("{:#x}", key.0), + len, + "a buffer's host copy is in the card's memory" + ); + let card = Card { + staging: buffer, + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size, + }; + (on_card, Some(card)) + } + None => (buffer, None), + }; // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; if len >= 16 << 20 { tracing::info!( - "large buffer copied to the host: start={:#x}, len={len}", - key.0 + start = format_args!("{:#x}", key.0), + len, + "large buffer copied to the host" ); } else { tracing::debug!( @@ -461,80 +2934,330 @@ pub(crate) fn find(address: u64, len: u64) -> Option> { "buffer copied to the host" ); } - entry.shadow = Some(Arc::new(Shadow::new(buffer, data, gpu, key.0, len))); + let mut shadow = Shadow::new(buffer, data, gpu, key.0, len); + shadow.card = card; + let shadow = Arc::new(shadow); + if shadow.card.is_some() { + CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + } + entry.shadow = Some(shadow); } entry.shadow.clone() } -/// Titles also use memory outside any buffer object as GPU memory (Grand -/// Theft Auto VI's interface vertices, from its own allocator). Such memory +/// Titles also use memory outside any buffer object as GPU memory ( +/// the title's interface vertices, from its own allocator). Such memory /// gets copies of the aligned windows it touches. -/// shortcut: copies of windows are never freed; key them to the title's -/// allocations if memory use grows. +/// A window nothing names any more is let go ([`let_go_idle`]). +/// shortcut: a window is 4 MiB however little of it is read (the memory +/// line says how much was ever asked for, and how much was ever copied); +/// [`window`] cuts the windows of asks that give a length on a finer grid. const WINDOW: u64 = 4 << 20; -/// Copies of title memory outside buffers, by (start, length). -static LOOSE: Mutex>> = Mutex::new(BTreeMap::new()); +/// The grid the windows of asks with a length are cut on, in bytes: 4 MiB +/// unless `VICTORY_WINDOW_KB` names a smaller power of two (64 at least). +/// A window is the PC's memory, all of it, however little of it is read: +/// 803 windows held 3.3 GB in run 60's gameplay, and all that was ever +/// asked for in them lay within 1.6 GB. On a grid of 1 MiB or 256 KiB a +/// window ends nearer to what is read. An ask without a length keeps the +/// 4 MiB grid whatever is set: a root view reads from its address to its +/// window's end, and mesh streams bound that way reach megabytes. +/// shortcut: the default stays 4 MiB until a run with the memory line's +/// window counts has shown what the finer grids give; the same memory +/// asked for with different ranges then lies in more than one window. +fn window() -> u64 { + static GRID: std::sync::OnceLock = std::sync::OnceLock::new(); + *GRID.get_or_init(|| { + let kb = std::env::var("VICTORY_WINDOW_KB").ok().and_then(|v| v.trim().parse::().ok()); + grid(kb) + }) +} + +/// The window grid in bytes for a setting in KiB: a power of two from +/// 64 KiB to 4 MiB, 4 MiB for anything else. +fn grid(kb: Option) -> u64 { + match kb { + Some(kb) if kb.is_power_of_two() && (64..=4096).contains(&kb) => kb << 10, + _ => WINDOW, + } +} + +/// The window (start, bytes) of title memory for an ask of `[address, +/// end)` on a grid of `grid` bytes. +fn window_of(address: u64, end: u64, grid: u64) -> (u64, u64) { + let start = address & !(grid - 1); + (start, end.next_multiple_of(grid) - start) +} + +/// Whether the window of an ask without a length begins at the ask instead +/// of at the 4 MiB line below it. Such an ask (a root view) reads from its +/// address to the end of its 4 MiB cell; what lies below the lowest +/// address ever asked for in the cell is memory the host zeroed and nothing +/// reads (513 of run 65's 782 windows were asked for that way, 2,052 MB; +/// of all windows' 3,236 MB, 1,988 MB were ever copied). With this on, the +/// window is the cell's tail from the ask's step on ([`TAIL_STEP`]); an ask +/// lower in the cell later makes a longer tail, which every ask from then +/// on takes, and the shorter one goes when nothing holds it any more. +/// shortcut: off unless `VICTORY_WINDOW_TAILS=1`. A longer tail is another +/// host buffer than the shorter one: what was bound to the shorter stays +/// right only because every list brings up to date the copy it bound +/// (`draw.rs` keeps a root view's copy with its slot). It pays only +/// together with `VICTORY_WINDOW_KB` below 4096: on the 4 MiB grid an ask +/// with a length in the same cell makes the whole cell's window, and the +/// tail is that. +fn tails() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOW_TAILS").is_some_and(|v| v == "1")) +} + +/// Tails begin on multiples of this. A longer tail is a new host buffer, +/// filled from title memory from its first byte to its last: begun on the +/// 64 KiB page of each ask, a cell whose asks came from the top down made +/// up to 63 of them, one after the other (part of run 71's copies). On +/// this step it is 15 at most, and a tail holds up to 192 KiB it did not +/// need. +const TAIL_STEP: u64 = 256 << 10; + +/// The window (start, bytes) a tail ask at `address` makes: from the ask's +/// step ([`TAIL_STEP`]) to the end of its 4 MiB cell. +fn tail_of(address: u64, end: u64) -> (u64, u64) { + let (cell, len) = window_of(address, end, WINDOW); + let start = address & !(TAIL_STEP - 1); + (start, cell + len - start) +} + +/// Of `windows` (start, bytes), the one an ask of `[address, end)` that +/// may take any window takes ([`find_any`]): the longest that holds the +/// whole range. +fn holder(windows: impl Iterator, address: u64, end: u64) -> Option<(u64, u64)> { + windows + .filter(|&(start, bytes)| start <= address && start + bytes >= end) + .max_by_key(|&(start, bytes)| (bytes, std::cmp::Reverse(start))) +} -/// The number and total size of registered and loose host copies retained. +/// Whether windows may be smaller than their 4 MiB cell (a finer grid, or +/// tails): only then is there more than one window to choose from. +fn fine() -> bool { + tails() || window() < WINDOW +} + +/// For the memory line: the bytes of title memory the windows alive lie +/// over (each byte once), beside the windows' own bytes in +/// [`memory`]: the difference is memory that is in more than one window, +/// which is copied once for each. #[cfg(feature = "diagnostics")] -pub(crate) fn cache_stats() -> (usize, u64, usize, u64) { - let (registered_count, registered_bytes) = buffers() - .values() - .filter_map(|entry| entry.shadow.as_ref()) - .fold((0usize, 0u64), |(count, bytes), shadow| { - (count + 1, bytes.saturating_add(shadow.len)) - }); - let (loose_count, loose_bytes) = LOOSE - .lock() - .unwrap_or_else(|e| e.into_inner()) - .values() - .fold((0usize, 0u64), |(count, bytes), shadow| { - (count + 1, bytes.saturating_add(shadow.len)) - }); - (registered_count, registered_bytes, loose_count, loose_bytes) +pub(crate) fn window_cover() -> u64 { + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + cover(loose.keys().copied()) +} + +/// The bytes `windows` (start, bytes; in order of start) lie over, each +/// byte once. +#[cfg_attr(not(any(test, feature = "diagnostics")), allow(dead_code))] +fn cover(windows: impl Iterator) -> u64 { + let (mut covered, mut reached) = (0, 0); + for (start, bytes) in windows { + let end = start + bytes; + if end > reached { + covered += end - start.max(reached); + reached = end; + } + } + covered +} + +/// Of `windows` (start, bytes; in order), the longest tail a tail ask at +/// `address` can take: the first that begins in the ask's cell at or below +/// the ask's page and ends where the cell ends. +fn longest_tail(windows: impl Iterator, address: u64, end: u64) -> Option<(u64, u64)> { + let (cell, len) = window_of(address, end, WINDOW); + let step = address & !(TAIL_STEP - 1); + windows + .filter(|&(start, bytes)| start >= cell && start <= step && start + bytes == cell + len) + .min() } -fn loose(address: u64, end: u64) -> Option> { - let start = address & !(WINDOW - 1); - let len = end.next_multiple_of(WINDOW) - start; +/// Copies of title memory outside buffers, by (start, length). +static LOOSE: Mutex>> = Mutex::new(BTreeMap::new()); + +fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option> { let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let (cell, _) = window_of(address, end, WINDOW); + let named = window_of(address, end, if unsized_ask { WINDOW } else { window() }); + let (start, len) = if unsized_ask && tails() { + let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key); + longest_tail(there, address, end).unwrap_or_else(|| tail_of(address, end)) + } else if any && fine() && !unsized_ask { + // The windows that begin in the ask's cell at or below the ask (one + // that begins in a cell below and reaches this far is passed over: + // the ask then makes its own). + let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key); + holder(there, address, end).unwrap_or(named) + } else { + named + }; + // Under the lock, with the handing out: see `let_go_idle`. + let note = |shadow: &Shadow| { + shadow.used.store(crate::host::moment(), Ordering::Relaxed); + shadow.asked[0].fetch_min(address, Ordering::Relaxed); + shadow.asked[1].fetch_max(end, Ordering::Relaxed); + if unsized_ask { + shadow.unsized_asks.fetch_add(1, Ordering::Relaxed); + } + }; if let Some(shadow) = map.get(&(start, len)) { + note(shadow); return Some(shadow.clone()); } - let host = host()?; - let Some((buffer, data)) = host.shared_buffer(len) else { - tracing::warn!( - address = format_args!("{start:#x}"), - len, - "could not allocate host copy for loose title memory" - ); - return None; - }; + // In place, if asked for and the window's memory can be opened: the + // window is the title's own memory, with nothing to copy. + if let Some(placed) = crate::inplace::place_for(start, len, true) { + let shadow = Arc::new(Shadow::placed(placed, start, len, true)); + note(&shadow); + map.insert((start, len), shadow.clone()); + return Some(shadow); + } + let (buffer, data) = host()?.shared_buffer(len)?; crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}")); + // With room for windows on the card (`window_card_most`): shaders get a + // buffer there, and the one just made is the CPU's side. + let (buffer, card) = match window_card_for(len) { + Some(on_card) => { + crate::host::name(&on_card, || format!("title memory {start:#x}+{len:#x} on the card")); + let card = Card { + staging: buffer, + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size: len, + }; + (on_card, Some(card)) + } + None => (buffer, None), + }; // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - tracing::debug!("loose memory copied to the host: start={start:#x}, len={len}"); - let shadow = Arc::new(Shadow::new(buffer, data, gpu, start, len)); + tracing::debug!( + start = format_args!("{start:#x}"), + len, + "loose memory copied to the host" + ); + let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.window = true; + shadow.card = card; + let shadow = Arc::new(shadow); + if shadow.card.is_some() { + CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + } + note(&shadow); map.insert((start, len), shadow.clone()); Some(shadow) } -/// Every host copy of title memory made so far (buffers' and loose -/// windows'), for the address map. -pub(crate) fn all() -> Vec> { - let mut out: Vec> = buffers() - .values() - .filter_map(|e| e.shadow.clone()) - .collect(); - out.extend( - LOOSE - .lock() - .unwrap_or_else(|e| e.into_inner()) - .values() - .cloned(), - ); - out +#[cfg(test)] +mod window_tests { + use super::{WINDOW, cover, grid, holder, longest_tail, tail_of, window_of}; + + /// An ask that may take any window takes the longest that holds all of + /// it, and none that holds only a part. + #[test] + fn an_ask_takes_the_longest_window_that_holds_it() { + let cell = 0xd_1200_0000u64; + let (ask, end) = (cell + 0x9_0000, cell + 0xb_0000); + assert_eq!(holder([].into_iter(), ask, end), None); + let there = [ + (cell, 0x4_0000), // ends below the ask + (cell + 0x8_0000, 0x2_0000), // holds its first half only + (cell + 0x8_0000, 0x4_0000), // holds it + (cell + 0x4_0000, 0x10_0000), // holds it, longer + (cell + 0xa_0000, 0x40_0000), // begins above it + ]; + assert_eq!(holder(there.into_iter(), ask, end), Some((cell + 0x4_0000, 0x10_0000))); + // Of two as long, the one that begins lower. + let two = [(cell + 0x8_0000, 0x8_0000), (cell + 0x4_0000, 0x8_0000)]; + assert_eq!(holder(two.into_iter(), ask, end), Some((cell + 0x4_0000, 0x8_0000))); + } + + /// What windows lie over counts each byte once. + #[test] + fn overlapping_windows_cover_their_memory_once() { + assert_eq!(cover([].into_iter()), 0); + let apart = [(0x10_0000u64, 0x4_0000u64), (0x20_0000, 0x4_0000)]; + assert_eq!(cover(apart.into_iter()), 0x8_0000); + // One inside another, one overlapping its end, one touching. + let over = [ + (0x10_0000u64, 0x10_0000u64), + (0x14_0000, 0x4_0000), + (0x1c_0000, 0x8_0000), + (0x24_0000, 0x4_0000), + ]; + assert_eq!(cover(over.into_iter()), 0x18_0000); + } + + /// A tail runs from the ask's page to the end of its 4 MiB cell, and an + /// ask takes the longest tail there is that holds it. + #[test] + fn tails_run_to_the_cells_end_and_the_longest_is_taken() { + let cell = 0xd_1200_0000u64; + let ask = cell + 0x12_3456; + assert_eq!(tail_of(ask, ask + 1), (cell + 0x10_0000, WINDOW - 0x10_0000)); + // The cell's first page: the whole cell, the window there always was. + assert_eq!(tail_of(cell + 0xffff, cell + 0x1_0000), (cell, WINDOW)); + let end = cell + WINDOW; + let tail = |from: u64| (cell + from, WINDOW - from); + // Nothing there, or only tails that begin above the ask. + assert_eq!(longest_tail([].into_iter(), ask, ask + 1), None); + assert_eq!(longest_tail([tail(0x20_0000)].into_iter(), ask, ask + 1), None); + // The longest of those that hold the ask; windows that do not reach + // the cell's end (cut on a finer grid for asks with a length) and + // windows of other cells are not tails. + let there = [ + (cell - WINDOW, WINDOW), + (cell, 0x4_0000), + tail(0x8_0000), + tail(0x10_0000), + (cell + 0x10_0000, 0x4_0000), + tail(0x20_0000), + ]; + assert_eq!(longest_tail(there.into_iter(), ask, ask + 1), Some(tail(0x8_0000))); + let (start, bytes) = tail(0x8_0000); + assert!(start <= ask && start + bytes == end); + // The whole cell's window is the longest tail of all. + let with_whole = [(cell, WINDOW), tail(0x8_0000)]; + assert_eq!(longest_tail(with_whole.into_iter(), ask, ask + 1), Some((cell, WINDOW))); + } + + /// The setting takes powers of two from 64 KiB to 4 MiB; anything else + /// leaves the grid as it was. + #[test] + fn the_grid_is_a_power_of_two_or_the_default() { + assert_eq!(grid(None), WINDOW); + assert_eq!(grid(Some(4096)), WINDOW); + assert_eq!(grid(Some(1024)), 1 << 20); + assert_eq!(grid(Some(256)), 256 << 10); + assert_eq!(grid(Some(64)), 64 << 10); + for bad in [0, 32, 100, 1000, 8192] { + assert_eq!(grid(Some(bad)), WINDOW, "{bad}"); + } + } + + /// A window holds its ask and is cut on the grid; on the default grid + /// it is the window there always was. + #[test] + fn windows_hold_their_ask_on_the_grid() { + let (address, end) = (0xd_1234_5678u64, 0xd_1234_5678u64 + 0x9000); + assert_eq!(window_of(address, end, WINDOW), (0xd_1200_0000, 4 << 20)); + assert_eq!(window_of(address, end, 1 << 20), (0xd_1230_0000, 1 << 20)); + assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 256 << 10)); + // An ask across a grid line takes both cells. + let end = address + 0x4_0000; + assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 512 << 10)); + for g in [64u64 << 10, 256 << 10, 1 << 20, WINDOW] { + let (start, len) = window_of(address, end, g); + assert!(start <= address && start + len >= end); + assert!(start % g == 0 && len % g == 0); + } + } } /// For device-removed reports: the copy of title memory whose host range diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 39ee5bb..34e7d51 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -7,24 +7,17 @@ //! //! "Changed" means a page of the memory was written since the last detiling //! ([`crate::watch`]), in write-watched memory; in physical-page views, -//! which cannot be watched, a content hash of each page at every -//! submission that samples it. Only the subresources whose memory holds a -//! changed page are detiled again (and, when watched, only the changed -//! pages read again). +//! which cannot be watched, a content hash of the whole memory at every +//! submission that samples it. //! -//! shortcut: a changed subresource is detiled whole, not just its blocks in -//! the pages written, and every subresource is still copied into the host -//! texture. Only textures read through descriptor tables are brought up to date +//! shortcut: a change detiles the whole texture, not the pages written. +//! Only textures read through descriptor tables are brought up to date //! (directly indexed views are not known per draw); plane 0 is uploaded //! (every mip and array slice), depth and stencil planes are not. use std::collections::HashMap; -use std::ops::Range; use std::sync::{Arc, Mutex}; -#[cfg(test)] -use victory_formats::texture::Error; -use victory_formats::texture::Layout; use windows::Win32::Graphics::Direct3D12::*; use crate::host::{HostList, host}; @@ -42,108 +35,37 @@ macro_rules! once { pub(crate) struct Staging { buffer: ID3D12Resource, /// Its bytes. - size: usize, + #[cfg(feature = "diagnostics")] + size: u64, data: *mut u8, - footprints: Vec, - layout: Layout, + footprints: Vec, + rows: Vec, + layout: victory_formats::texture::Layout, /// Mips per array slice. mips: u32, - /// Per subresource, the byte ranges of the memory it is detiled from. - extents: Vec>>, - /// Top console mips omitted from the host copy. - mip_drop: u32, + /// The staging buffer's bytes (counted in `STAGED` while it lives). + bytes: u64, memory: *const u8, last: Mutex, -} - -struct UploadFootprint { - placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, - range: Range, - depth_pitch: usize, -} - -impl UploadFootprint { - fn new( - placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, - rows: u32, - row_size: u64, - total: usize, - ) -> Option { - let pitch = placed.Footprint.RowPitch as usize; - let row_size = usize::try_from(row_size).ok()?; - let (len, depth_pitch) = footprint_size(pitch, rows, placed.Footprint.Depth, row_size)?; - let start = usize::try_from(placed.Offset).ok()?; - let end = start.checked_add(len)?; - (end <= total).then_some(Self { - placed, - range: start..end, - depth_pitch, - }) - } + /// Whether the staging buffer was detiled since a submitted list last + /// uploaded it, and whether one has uploaded it at all: a list records + /// the upload only then. (Every list that sampled a title texture + /// uploaded all of it again, changed or not: 5,411 subresource copies + /// of 1,120 textures in one frame of run 18.) + dirty: std::sync::atomic::AtomicBool, + uploaded: std::sync::atomic::AtomicBool, + /// When a list last recorded a use of it (`crate::host::moment`). + used: std::sync::atomic::AtomicU64, } /// What a texture's staging buffer holds: the hash of the memory detiled -/// (memory not watched), or the write-watch asking it was detiled after, -/// with room to read the memory into. +/// (memory not watched), or the write-watch asking it was detiled after. #[derive(Default)] struct Last { - hashes: Vec, + hash: Option, asked: u64, - read: Vec, - /// Generation of the contents in the staging buffer. - detiled: u64, - /// Generation the host texture was last uploaded from. - uploaded: u64, -} - -/// Whether any of `changed` overlaps any of `extents` (both sorted). -fn overlaps(extents: &[Range], changed: &[Range]) -> bool { - let (mut i, mut j) = (0, 0); - while i < extents.len() && j < changed.len() { - let (e, c) = (&extents[i], &changed[j]); - if e.start < c.end && c.start < e.end { - return true; - } - if e.end <= c.end { - i += 1; - } else { - j += 1; - } - } - false -} - -/// The parts of `[0, len)` in which `a` and `b`, hashes of its `page`-byte -/// parts, differ; `None` when they do not hash the same parts. -fn changed_pages( - a: &[blake3::Hash], - b: &[blake3::Hash], - page: usize, - len: usize, -) -> Option>> { - (a.len() == b.len()).then(|| { - (0..a.len()) - .filter(|&i| a[i] != b[i]) - .map(|i| i * page..((i + 1) * page).min(len)) - .collect() - }) -} - -/// `[start, start + len)`'s byte ranges, relative to `start`, of the -/// `page`-byte pages numbered `pages` (in order). -fn page_ranges( - pages: impl Iterator, - page: usize, - start: usize, - len: usize, -) -> Vec> { - pages - .map(|p| { - let end = ((p + 1) * page).min(start + len); - (p * page).max(start) - start..end.saturating_sub(start) - }) - .filter(|r| r.start < r.end) - .collect() + /// The frame a partly mapped texture was last read in. + partial: Option, } // SAFETY: the staging mapping is written only at submission, under @@ -154,272 +76,484 @@ unsafe impl Sync for Staging {} static STAGING: Mutex>>> = Mutex::new(None); -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum HostWrite { - /// Write-watched memory: the write-watch asking when the host copy happened. - Watched { - start: usize, - end: usize, - asked: u64, - }, - /// Non-watched memory (physical-page view): content hash at the host copy. - Hashed { - memory: usize, - size: usize, - hash: Option, - }, - /// Layout unknown or unsupported: keep host contents until released. - Fixed, +/// The buffer a texture the host writes is copied through into the texture +/// of a view the title placed in its memory in another format +/// ([`alias`]): every level of every layer as each of the two formats lays +/// it out for a copy (the same bytes: the texels are as wide), the written +/// texture's layout first. +struct Through { + buffer: ID3D12Resource, + parts: Vec<( + D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + )>, } -/// Textures the host GPU wrote by a copy or resolve: their contents stay on -/// the host until the title writes their memory again. -static HOST_WRITTEN: Mutex>> = Mutex::new(None); +/// The most levels times layers [`alias`] copies (a cube of nine levels). +const ALIAS_PARTS: u32 = 54; -fn host_write_state(memory: *const u8, size: usize) -> HostWrite { - let start = memory as usize; - if let Some((now, _)) = crate::watch::writes(start, start + size, false) { - return HostWrite::Watched { - start, - end: start + size, - asked: now, - }; - } - let hash = committed(memory, size).then(|| { - // SAFETY: committed memory of the texture's layout size. - let tiled = unsafe { std::slice::from_raw_parts(memory, size) }; - blake3::hash(tiled) - }); - HostWrite::Hashed { - memory: start, - size, - hash, - } -} +// SAFETY: a device-local buffer only lists record copies with. +unsafe impl Send for Through {} +// SAFETY: as above. +unsafe impl Sync for Through {} -/// Whether `resource`'s host copy is still newer than its title memory. -fn still_host_written(resource: usize) -> bool { - let state = HOST_WRITTEN - .lock() - .unwrap_or_else(|e| e.into_inner()) - .as_ref() - .and_then(|map| map.get(&resource).copied()); - let Some(state) = state else { +/// The copy buffers of [`alias`], by the placed view's texture. +static THROUGH: Mutex>>> = Mutex::new(None); + +/// Brings `placed`, the texture of a view the title placed in the memory +/// of `source` in another format (`crate::resource::alias_of`), up to date +/// with what the host wrote to `source`: the texels of every level and +/// layer are copied as they are, through a buffer (the host copies between +/// two formats of one texel width in no other way). Recorded the first time +/// the list reads the view +/// and again whenever the list used `source` in another way since (wrote +/// it, or read it itself). Leaves `placed` in the copy destination state, +/// as [`upload`] does. False if the copy cannot be made: the caller fills +/// the texture from title memory, as before. +pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { + const TARGET_OR_UNORDERED: u32 = 0x4 | 0x8; + const COPY_DEST: u32 = 0x400; + const COPY_SOURCE: u32 = 0x800; + let (Some(to), Some(from)) = ( + crate::resource::host_resource(placed), + crate::resource::host_resource(source), + ) else { return false; }; - let unchanged = match state { - HostWrite::Fixed => true, - HostWrite::Watched { start, end, asked } => crate::watch::writes(start, end, false) - .is_none_or(|(_, written)| written.iter().all(|&(_, w)| w <= asked)), - HostWrite::Hashed { memory, size, hash } => { - if !committed(memory as *const u8, size) { - true - } else { - // SAFETY: committed memory of the texture's layout size. - let tiled = unsafe { std::slice::from_raw_parts(memory as *const u8, size) }; - hash == Some(blake3::hash(tiled)) + let Some(host) = host() else { return false }; + let through = { + let mut map = THROUGH.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(HashMap::new); + match map.get(&(placed as usize)) { + Some(through) => through.clone(), + None => { + // SAFETY: live textures. + let (of_from, of_to) = unsafe { (from.GetDesc(), to.GetDesc()) }; + // Levels times layers (a volume's slices are one part). + let count = |d: &D3D12_RESOURCE_DESC| { + let layers = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + 1 + } else { + u32::from(d.DepthOrArraySize) + }; + u32::from(d.MipLevels) * layers + }; + let parts = count(&of_from); + if parts == 0 || parts > ALIAS_PARTS || parts != count(&of_to) { + return false; + } + let mut rows = [(); 2] + .map(|()| vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); parts as usize]); + let mut bytes = [0u64; 2]; + // SAFETY: plain queries; the out pointers are ours and + // hold `parts` layouts each. + unsafe { + host.device.GetCopyableFootprints( + &of_from, + 0, + parts, + 0, + Some(rows[0].as_mut_ptr()), + None, + None, + Some(&mut bytes[0]), + ); + host.device.GetCopyableFootprints( + &of_to, + 0, + parts, + 0, + Some(rows[1].as_mut_ptr()), + None, + None, + Some(&mut bytes[1]), + ); + } + let alike = rows[0].iter().zip(&rows[1]).all(|(a, b)| { + let (fa, fb) = (a.Footprint, b.Footprint); + a.Offset == b.Offset + && (fa.Width, fa.Height, fa.Depth, fa.RowPitch) + == (fb.Width, fb.Height, fb.Depth, fb.RowPitch) + }); + if bytes[0] == 0 || bytes[0] != bytes[1] || !alike { + return false; + } + let Some(buffer) = host.uav_buffer(bytes[0]) else { + return false; + }; + crate::host::name(&buffer, || { + format!( + "alias copy {}x{} f{} to f{}", + of_from.Width, of_from.Height, of_from.Format.0, of_to.Format.0 + ) + }); + tracing::info!( + view = ?placed, + texture = ?source, + width = of_from.Width, + height = of_from.Height, + parts, + written_as = of_from.Format.0, + read_as = of_to.Format.0, + "a view placed in the memory of a texture the host writes, in another format: read from that texture by a copy on the host" + ); + let [of_written, of_read] = rows; + let through = Arc::new(Through { + buffer, + parts: of_written.into_iter().zip(of_read).collect(), + }); + map.insert(placed as usize, through.clone()); + through } } }; - if !unchanged { - let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(map) = map.as_mut() - && map.get(&resource) == Some(&state) - { - map.remove(&resource); + let first = list.first_use(placed as usize); + // The source's first use in the list records nothing (its prelude + // brings it to the state); a use in another way since the last copy + // shows as a change of state. + let before = list.transition(source, COPY_SOURCE).map(|(texture, before)| { + let state = crate::host::legal_state(texture, COPY_SOURCE); + let barrier = crate::host::transition( + texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(state as i32), + ); + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + before + }); + if !first && before.is_none() { + return true; + } + crate::list::ensure_state(list, placed, COPY_DEST); + let part = |texture: &ID3D12Resource, index: usize| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: index as u32, + }, + }; + let rows = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(&through.buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: *row, + }, + }; + let (common, read, written) = ( + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + #[cfg(feature = "diagnostics")] + list.note_op(|| format!("alias copy of {source:?} into {placed:?}")); + // SAFETY: an open list and live resources; the buffer is as big as + // the footprints and rests in the common state between copies. + unsafe { + list.list + .ResourceBarrier(&[crate::host::transition(&through.buffer, common, written)]); + for (index, (of_written, _)) in through.parts.iter().enumerate() { + list.list + .CopyTextureRegion(&rows(of_written), 0, 0, 0, &part(from, index), None); + } + list.list + .ResourceBarrier(&[crate::host::transition(&through.buffer, written, read)]); + for (index, (_, of_read)) in through.parts.iter().enumerate() { + list.list + .CopyTextureRegion(&part(to, index), 0, 0, 0, &rows(of_read), None); } + list.list + .ResourceBarrier(&[crate::host::transition(&through.buffer, read, common)]); } - unchanged -} - -/// A host copy or resolve writes `resource`. -pub(crate) fn host_written(resource: This) { - if crate::resource::host_resource(resource).is_some_and(|t| !title_written(t)) { - return; + list.keep(&through.buffer); + // A draw that also writes the source (a view of it handled before + // this one) needs it in that state again; the next read of the alias + // then copies once more, as it must after a write. + if let Some(before) = before + && before & TARGET_OR_UNORDERED != 0 + { + crate::list::ensure_state(list, source, before); } - let state = crate::resource::texture_memory(resource) - .and_then(|(memory, desc)| { - let layout = crate::resource::texture_layout(&desc)?.planes[0] - .layout - .clone(); - (!layout.desc.swizzle.xor()).then(|| host_write_state(memory, layout.size as usize)) - }) - .unwrap_or(HostWrite::Fixed); - let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - map.get_or_insert_with(HashMap::new) - .insert(resource as usize, state); + true } -/// The title released a resource. -pub(crate) fn forget(resource: usize) { - let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(map) = map.as_mut() { - map.remove(&resource); - } - let mut host_written = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(host_written) = host_written.as_mut() { - host_written.remove(&resource); - } +/// Whether a texture refresh that finds the runtime remapping title memory +/// goes on without waiting for it (`VICTORY_TEXTURE_NO_WAIT=1`; off by +/// default). +/// +/// A texture whose memory is all mapped is read in place, under a lock +/// the runtime takes alone while it changes a mapping +/// (`crate::watch::title_memory_reading`), so that no page goes away under +/// the read. While the world streams in the runtime remaps all the time, +/// and each of the frame's 150-360 refreshes waited for it: runs 99-101 +/// have 4, 15 and 16 frame lines with over 300 ms of "textures", up to +/// 3,708 ms, and on every one of them the wait for this lock is the whole +/// of it (1,345 of 1,381 ms; 3,630 of 3,708; the write-watch askings 3-12 +/// ms, the texture's own lock 0). +/// +/// With the switch the refresh asks for the lock without waiting. If the +/// runtime has it, the texture is read through the kernel instead, which +/// needs no lock: it fails if a page is not there, and then the texture is +/// left as it is and read at its next refresh, a frame later. A read +/// through the kernel costs about 0.6 ms a megabyte against 0.3 in place. +/// +/// What changes for the picture: a texture that arrives while the runtime +/// is remapping may show a frame later. It never shows partly read. +fn no_wait() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_NO_WAIT").is_some_and(|v| v == "1")) } -/// Whether `resource`'s host copy takes its contents from title memory: -/// a texture the host GPU does not render to or write. -pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { - // SAFETY: a live resource. - title_written_flags(unsafe { texture.GetDesc() }.Flags) +/// Since the last frame-rate line, with [`no_wait`]: refreshes that read +/// through the kernel because title memory was being remapped, and those +/// left for the next refresh because a page was not there. +pub(crate) static UNLOCKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Since the last frame-rate line, of texture refreshes on every thread, in +/// microseconds: waiting for the texture's own lock (another thread is +/// refreshing the same texture), asking the write watch and the guards, +/// waiting for title memory to hold still (the lock the runtime takes +/// alone while it remaps, `crate::watch::title_memory_reading`), and the +/// refreshes in all. +/// +/// While the world streams in, the frame line's "textures" is seconds a +/// frame in some runs and tenths in others for the same megabytes (2,566 +/// ms for 110 MB in run 93, 314 ms for 132 MB in run 91; before these +/// counters, runs 81, 83, 85 and 94 each had lines of 1.5-2.9 s), and the +/// submitting thread is not running while it lasts (run 93: 240-310 ms of +/// its own time a frame beside 1,100-1,800 ms of "textures"): it waits. +/// These say for what. +pub(crate) static REFRESH_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// `f`'s result, its time added to [`REFRESH_WAITS`]' place `slot`. +fn waited(slot: usize, f: impl FnOnce() -> T) -> T { + let started = std::time::Instant::now(); + let out = f(); + REFRESH_WAITS[slot].fetch_add(started.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + out } -fn title_written_flags(flags: D3D12_RESOURCE_FLAGS) -> bool { - let host_writable = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET - | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL - | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - (flags & host_writable) == D3D12_RESOURCE_FLAG_NONE +thread_local! { + /// Room to read a texture's memory into: one buffer per submitting + /// thread. Each texture kept its own, a second copy in memory of every + /// write-watched or partly mapped texture ever sampled, for the run. + static READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } -/// A fingerprint of the title memory `[at, at + len)`, never 0: of all of -/// it up to 48 KiB, else of 16 KiB at its start, its middle and its end -/// (a texture streams in whole mips; the small ones lie first). Read -/// through the kernel, so pages not there count as zeros. -pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { - const WINDOW: usize = 16 << 10; - thread_local! { - static READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; - } - let len = len as usize; - let mut hasher = blake3::Hasher::new(); +/// Calls `f` with `size` bytes of this thread's read buffer (their +/// contents are whatever the last texture left). +fn with_read(size: usize, f: impl FnOnce(&mut [u8]) -> R) -> R { READ.with(|read| { let mut read = read.borrow_mut(); - read.resize(3 * WINDOW, 0); - let mut take = |from: usize, bytes: usize| { - read[..bytes].fill(0); - crate::host::copy_mapped( - read.as_mut_ptr(), - (at as usize + from) as *const u8, - bytes, - false, - ); - hasher.update(&read[..bytes]); - }; - if len <= 3 * WINDOW { - take(0, len); - } else { - take(0, WINDOW); - take((len / 2) & !0xfff, WINDOW); - take(len - WINDOW, WINDOW); + if read.len() < size { + read.resize(size, 0); } - }); - let hash = hasher.finalize(); - let mut first = [0u8; 8]; - first.copy_from_slice(&hash.as_bytes()[..8]); - u64::from_le_bytes(first) | 1 + f(&mut read[..size]) + }) } -/// Where a staged title texture's memory is: address and bytes. -pub(crate) fn staged_memory(resource: This) -> Option<(u64, u64)> { - let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); - let staging = map.as_ref()?.get(&(resource as usize))?; - Some((staging.memory as u64, staging.layout.size)) +/// Whether a texture all of whose memory is mapped is read through the +/// kernel's copy instead of in place (`VICTORY_TEXTURE_COPY=1`; off by +/// default). Round 3 of the memory work read every such texture that way +/// to be safe from pages taken away under the read; it cost 0.6 ms per MB +/// against 0.3 in place (90-105 ms a frame while the world streams in, runs +/// 72 and 73, against 20-40), and both runs with it lost the graphics +/// device, for a reason not found. The read in place is safe now for +/// another reason (`crate::watch::title_memory_reading`); this switch is +/// left to tell whether the copy was what lost the device. +fn through_copy() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_COPY").is_some_and(|v| v == "1")) } -/// Frames after a whole upload of a texture at which its memory is looked -/// at again, each counted from the look before. -const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400]; +/// Calls `f` with the `size` bytes of title memory at `memory`, read +/// through the kernel into this thread's read buffer; pages that are not +/// there read as zeros. The bytes are those a read in place would see. +fn with_title(memory: *const u8, size: usize, f: impl FnOnce(&[u8]) -> R) -> R { + with_read(size, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), memory, size, false); + f(read) + }) +} -/// Textures uploaded whole, looked at again while their memory may still -/// be streaming in with nothing to tell of it: resource -> (address, -/// bytes, fingerprint at the upload, looks that found it unchanged, frame -/// of the next look). -/// (Address, bytes, fingerprint at the upload, looks that found it -/// unchanged, frame of the next look) of one uploaded texture. -type Recheck = (u64, u64, u64, u8, u64); +/// Staging buffers alive (also those only a list still holds) and their +/// bytes. +static STAGED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; -static RECHECKS: Mutex>> = Mutex::new(None); +impl Drop for Staging { + fn drop(&mut self) { + use std::sync::atomic::Ordering::Relaxed; + STAGED[0].fetch_sub(1, Relaxed); + STAGED[1].fetch_sub(self.bytes, Relaxed); + } +} -/// Whether uploaded textures are looked at again after their upload -/// (`VICTORY_HEAP_RECHECK=0`: no). -fn heap_recheck() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_RECHECK").is_none_or(|v| v != "0")) +/// For the memory line: staging buffers alive, their bytes, and how many +/// of them their texture still has (the others wait for a list's reset). +#[cfg(feature = "diagnostics")] +pub(crate) fn memory() -> [u64; 3] { + use std::sync::atomic::Ordering::Relaxed; + let kept = STAGING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map_or(0, |map| map.len() as u64); + [STAGED[0].load(Relaxed), STAGED[1].load(Relaxed), kept] } -/// `resource` was uploaded whole: looked at again from frame `due` (the -/// title may fill the texture's memory only after it wrote the view, with -/// no descriptor write and nothing from the runtime to tell of it; the -/// host copy then kept what the memory held at the first look for the -/// rest of the run). -fn recheck_later(resource: This, due: u64) { - if !heap_recheck() { - return; - } - let Some((at, len)) = staged_memory(resource) else { - return; - }; - let print = fingerprint(at, len); - let mut map = RECHECKS.lock().unwrap_or_else(|e| e.into_inner()); - map.get_or_insert_with(HashMap::new) - .insert(resource as usize, (at, len, print, 0, due)); +/// Staging buffers let go as idle since the start, and their bytes. +static LET_GO: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// For the memory line: staging buffers let go as idle, and their bytes. +#[cfg(feature = "diagnostics")] +pub(crate) fn let_go() -> [u64; 2] { + use std::sync::atomic::Ordering::Relaxed; + [LET_GO[0].load(Relaxed), LET_GO[1].load(Relaxed)] } -/// The memory of a texture looked at again at `frame` changed since its -/// upload: the next refresh re-reads and re-detiles it whole, and the -/// caller uploads it again. Unchanged: the look is rescheduled -/// (`RECHECK_FRAMES`), or the looks end. -pub(crate) fn recheck_due(resource: This, frame: u64) -> bool { - if !heap_recheck() { - return false; +/// Lets go of the staging buffers no list recorded a use of for `IDLE_MS` +/// and `IDLE_FRAMES` frames and no list holds: a staging buffer is system memory the size of its +/// texture, kept so that an unchanged texture is not uploaded again, and +/// those of textures no longer sampled were kept for the run (2,246 of +/// them, 2.1 GB, at the end of run 24). The next list that samples such a +/// texture makes a staging buffer anew, detiles and uploads once more. +/// Called before a submission starts, by the thread that submits. +pub(crate) fn let_go_idle() { + use std::sync::atomic::Ordering::Relaxed; + const IDLE_FRAMES: u64 = 4; + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let Some(map) = map.as_mut() else { + return; + }; + if map.is_empty() { + return; } - let entry = { - let mut map = RECHECKS.lock().unwrap_or_else(|e| e.into_inner()); - let Some(map) = map.as_mut() else { - return false; - }; - let Some(entry) = map.get_mut(&(resource as usize)) else { - return false; - }; - if frame < entry.4 { - return false; + let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + // A list that recorded an upload or a check holds the staging until it + // is reset: one only the table holds is named by no list, recorded or + // running. + let (mut went, mut bytes) = (0u64, 0u64); + map.retain(|_, s| { + let keep = Arc::strong_count(s) > 1 + || !crate::host::long_ago(s.used.load(Relaxed), idle_ms, IDLE_FRAMES); + if !keep { + LET_GO[0].fetch_add(1, Relaxed); + LET_GO[1].fetch_add(s.bytes, Relaxed); + went += 1; + bytes += s.bytes; } - *entry + keep + }); + if went > 0 { + crate::host::trail(|| format!("sweep: {went} staging buffers of textures let go ({} KiB), held by no list", bytes >> 10)); + } +} + +/// Textures the host GPU wrote by a copy or resolve: their contents are on +/// the host, not in title memory, which stays as it was. +static HOST_WRITTEN: Mutex>> = Mutex::new(None); + +/// A host copy or resolve writes `resource`. +pub(crate) fn host_written(resource: This) { + let new = { + let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + set.get_or_insert_with(Default::default).insert(resource as usize) }; - let (at, len, print, looks, _) = entry; - if fingerprint(at, len) == print { - let mut map = RECHECKS.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(map) = map.as_mut() { - match RECHECK_FRAMES.get(usize::from(looks) + 1) { - Some(wait) => { - if let Some(entry) = map.get_mut(&(resource as usize)) { - entry.3 = looks + 1; - entry.4 = frame + wait; - } - } - None => { - map.remove(&(resource as usize)); - } - } + // Diagnostics (run 177): where its title memory is, for placed views + // the title reads that memory through ([`placed_in_host_written`]). + if new && let Some((at, desc)) = crate::resource::texture_memory(resource) { + // SAFETY: 56 bytes in the description's layout. + let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() }; + let bytes = crate::resource::placed_bytes(&words).unwrap_or(0); + if !at.is_null() && bytes > 0 { + HOST_WRITTEN_AT + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(at as u64, (bytes, words[4], words[6], words[7], words[8], resource as usize)); } - return false; } - { - let mut map = RECHECKS.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(map) = map.as_mut() { - map.remove(&(resource as usize)); +} + +/// The title memory of textures the host copied into, by address: bytes +/// and description words 4, 6, 7 and 8 (width, height, layers and levels, +/// format). +static HOST_WRITTEN_AT: Mutex> = + Mutex::new(std::collections::BTreeMap::new()); + +/// A texture the title placed at `address` (description words `desc`) was +/// made: says so once if it lies in the memory of a texture the host +/// copied into ([`host_written`]). Its own host copy is filled from title +/// memory, which the copy never reached: the copied texels are on the +/// card in the other texture, where no shader that reads this view finds +/// them. +pub(crate) fn placed_in_host_written(address: u64, desc: &[u32; 14]) { + let hit = { + let map = HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()); + map.range(..=address) + .next_back() + .filter(|(at, d)| address < **at + d.0) + .map(|(at, d)| (*at, *d)) + }; + if let Some((at, (bytes, width, height, layers_levels, format, _))) = hit { + static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 200 { + tracing::warn!( + view_address = format_args!("{address:#x}"), + view_offset = address - at, + view_width = desc[4], + view_height = desc[6], + view_layers_levels = format_args!("{:#x}", desc[7]), + view_format = desc[8], + copied_address = format_args!("{at:#x}"), + copied_bytes = bytes, + copied_width = width, + copied_height = height, + copied_layers_levels = format_args!("{layers_levels:#x}"), + copied_format = format, + "HERO LEAD: a placed texture view lies in the memory of a texture the host copied into: it is filled from title memory, which the copy never reached" + ); } } - // The incremental refresh asks the write-watch which pages changed; - // this write is one nothing told of. The next refresh re-reads the - // memory whole instead. - let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(staging) = map.as_ref().and_then(|map| map.get(&(resource as usize))) { - staging.last.lock().unwrap_or_else(|e| e.into_inner()).asked = 0; +} + +/// Whether the host GPU wrote `resource` by a copy or resolve +/// ([`host_written`]): its host copy cannot be made again from title +/// memory. +pub(crate) fn host_wrote(resource: usize) -> bool { + HOST_WRITTEN + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .is_some_and(|set| set.contains(&resource)) +} + +/// The title released a resource. +pub(crate) fn forget(resource: usize) { + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() { + map.remove(&resource); + } + let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(set) = set.as_mut() { + set.remove(&resource); + } + // Its memory may be given to other textures now (run 177: most of the + // "HERO LEAD" lines were views in memory a released texture had held). + HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, d| d.5 != resource); + let mut through = THROUGH.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(through) = through.as_mut() { + through.remove(&resource); } - tracing::warn!( - resource = format_args!("{:?}", resource as usize), - address = format_args!("{at:#x}"), - bytes = len, - looks, - "a texture changed after its upload with nothing to tell of it: uploaded again" - ); - true +} + +/// Whether `resource`'s host copy takes its contents from title memory: +/// a texture the host GPU does not render to or write. +pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { + const TARGET_DEPTH_UNORDERED: i32 = 0x7; + // SAFETY: a live resource. + unsafe { texture.GetDesc() }.Flags.0 & TARGET_DEPTH_UNORDERED == 0 } /// Records, once per list, the copy of `resource`'s staging buffer into @@ -427,22 +561,104 @@ pub(crate) fn recheck_due(resource: This, frame: u64) -> bool { /// submission if the memory changed. Leaves the texture in the copy /// destination state. pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { - if !list.first_use(resource as usize) || still_host_written(resource as usize) { + let host_written = HOST_WRITTEN + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .is_some_and(|set| set.contains(&(resource as usize))); + // shortcut: a texture the host copied into keeps the host's contents + // even if the title later writes its memory too. + if host_written || !list.first_use(resource as usize) { return; } let Some(staging) = staging(resource, texture) else { return; }; - let Some(copy) = crate::resource::host_copy(resource) else { + use std::sync::atomic::Ordering::Relaxed; + staging.used.store(crate::host::moment(), Relaxed); + // The host texture has the staging buffer's contents: only the check + // at submission is left, and what it finds changed the next list that + // samples the texture uploads (a frame late where every list of the + // frame was recorded before that check). + if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexSkipped, 1); + list.defer_texture(staging); return; - }; - // The copy itself is recorded at submission, in the first list prelude - // whose refreshed staging generation is not in the host texture yet. - list.defer_texture(staging, copy); - recheck_later(resource, crate::queue::presented() + RECHECK_FRAMES[0]); + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexUploads, 1); + const COPY_DEST: u32 = 0x400; + crate::list::ensure_state(list, resource, COPY_DEST); + // The staging buffer lives as long as `staging`, which the deferred + // refresh below holds until the list is reset. + for (i, footprint) in staging.footprints.iter().enumerate() { + #[cfg(feature = "diagnostics")] + { + let f = footprint.Footprint; + // SAFETY: live resources. + let (gpu, d) = unsafe { (staging.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 {}", + d.Width, + d.Height, + d.DepthOrArraySize, + d.Format.0, + d.MipLevels, + staging.footprints.len(), + staging.size, + footprint.Offset, + f.Width, + f.Height, + f.Depth, + f.RowPitch + ) + }, + (gpu + footprint.Offset, len), + ); + } + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: i as u32, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(&staging.buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: *footprint, + }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + // When the list is submitted, its copy takes what the staging buffer + // holds by then: noted before the check below, which sets `dirty` + // again if it detiles (the next list then uploads once more). + { + let staging = staging.clone(); + list.defer_host(move || { + staging.uploaded.store(true, Relaxed); + staging.dirty.store(false, Relaxed); + }); + } + // Once per submission however many of its lists sample the texture. + list.defer_texture(staging); } impl Staging { + /// The title memory the texture is read from: address and bytes. + pub(crate) fn memory(&self) -> (usize, usize) { + (self.memory as usize, self.layout.size as usize) + } + /// Detiles the texture memory into the staging buffer if it changed /// since the last time (and is mapped at all). pub(crate) fn refresh(&self) { @@ -456,96 +672,169 @@ impl Staging { /// Returns the bytes of title memory read. fn refresh_now(&self) -> usize { - let Ok(size) = usize::try_from(self.layout.size) else { - return 0; - }; + let whole = std::time::Instant::now(); + let read = self.refresh_timed(); + REFRESH_WAITS[3].fetch_add(whole.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + read + } + + fn refresh_timed(&self) -> usize { + let size = self.layout.size as usize; let start = self.memory as usize; - let Some(end) = start - .checked_add(size) - .filter(|_| size <= isize::MAX as usize) - else { - return 0; - }; - let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); + let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); let last = &mut *last; - if let Some((now, written)) = crate::watch::writes(start, end, false) { - let before = last.asked; - if before != 0 && written.iter().all(|&(_, w)| w <= before) { + if let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) { + if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { return 0; } last.asked = now; // Read through the copy, which stands unmapped pages: memory of // big pools is too slow to ask page by page. - if before == 0 || last.read.len() != size { - last.read.resize(size, 0); - crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false); - if self.detile(&last.read, None) { - last.detiled += 1; - } - #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::TexWatched, size as u64); - return size; - } - // The rest of the memory is as last read: read again only the - // pages written since, and detile what they hold. - let pages = written - .iter() - .filter(|&&(_, w)| w > before) - .map(|&(p, _)| p); - let changed = page_ranges(pages, crate::watch::PAGE, start, size); - let mut read = 0; - for r in &changed { - // SAFETY: `r` lies inside both the read copy and the - // texture's memory, each `size` bytes. - let (to, from) = unsafe { - ( - last.read.as_mut_ptr().add(r.start), - self.memory.add(r.start), - ) - }; - crate::host::copy_mapped(to, from, r.len(), false); - read += r.len(); - } - if self.detile(&last.read, Some(&changed)) { - last.detiled += 1; - } + with_read(size, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); + self.detile(read); + }); #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::TexWatched, read as u64); - return read; + crate::copystat::add(crate::copystat::C::TexWatched, size as u64); + return size; + } + // View memory has no write-watch, and a texture there was hashed + // whole at every check: 229 MB and 51 ms a frame in a gameplay view + // where two textures change (run 58). It is guarded now, as buffers + // in view memory are: a write of the title's to it faults once and + // is noted, a mapping is announced by the runtime. While neither + // happened the texture is as it was. What the guard cannot see (a + // write to the same pages through another view) is still found by + // the hash, which is taken every eighth frame only, by the + // texture's address, so the textures take turns. + // `VICTORY_TEXTURE_GUARD=0` hashes at every check, as before. + static GUARD: std::sync::OnceLock = std::sync::OnceLock::new(); + if *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) + && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) + { + const HASH_EVERY: u64 = 8; + let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked); + last.asked = now; + let turn = crate::frame::current().wrapping_add((start >> 16) as u64).is_multiple_of(HASH_EVERY); + if unwritten && !turn { + return 0; + } } + // From here on the texture's memory may be read in place. Held until + // that read is done: the runtime changes what title memory shows + // only with this taken alone, so what `committed` finds mapped + // stays mapped (see `crate::watch::title_memory_reading`; without + // it a page went between the asking and the read in runs 71 and + // 74). + let _mapped = if no_wait() { + // Not waited for: while the runtime remaps title memory the + // texture is read through the kernel instead, whole or not at + // all (`no_wait`). + let Some(mapped) = crate::watch::title_memory_reading_now() else { + return self.refresh_unlocked(last, size); + }; + mapped + } else { + waited(2, crate::watch::title_memory_reading) + }; if !committed(self.memory, size) { + // Partly mapped: a streamed texture with only some mips' pages + // there, the usual state while it streams in. Read through the + // copy, which stands unmapped pages (zeros), and upload what + // is there; nothing at all mapped changes nothing. + // shortcut: read again at most every 30 frames (reading around + // unmapped pages is slow, and nothing tells us when pages + // arrive): a mip that streams in shows up to 30 frames late. + let frame = crate::frame::current(); + if last.partial.is_some_and(|at| frame < at + 30) { + return 0; + } + last.partial = Some(frame); #[cfg(feature = "diagnostics")] - tracing::debug!( - memory = ?self.memory, - size, - desc = ?self.layout.desc, - "a sampled texture's memory is not committed" - ); - return 0; + crate::copystat::add(crate::copystat::C::TexHashed, size as u64); + let changed = with_read(size, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); + let hash = blake3::hash(read); + if last.hash == Some(hash) { + return false; + } + last.hash = Some(hash); + if read.iter().all(|&b| b == 0) { + return false; + } + self.detile(read); + true + }); + #[cfg(feature = "diagnostics")] + if changed { + crate::copystat::add(crate::copystat::C::TexChanged, size as u64); + } + let _ = changed; + return size; } - // SAFETY: committed memory of the texture's layout size. + if through_copy() { + return with_title(self.memory, size, |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; + } + last.hash = Some(hash); + self.detile(tiled); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexChanged, size as u64); + size + }); + } + // SAFETY: committed memory of the texture's layout size, and it + // stays committed while `_mapped` is held. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; - let page = crate::watch::PAGE; - let hashes: Vec = tiled.chunks(page).map(blake3::hash).collect(); + let hash = blake3::hash(tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); - if last.hashes == hashes { + if last.hash == Some(hash) { return size; } - let changed = changed_pages(&last.hashes, &hashes, page, size); - if self.detile(tiled, changed.as_deref()) { - last.detiled += 1; - } - last.hashes = hashes; + last.hash = Some(hash); + self.detile(tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); size } - /// Detiles `tiled` (the texture's memory) into the staging buffer: the - /// subresources whose memory overlaps `changed` (sorted byte ranges), - /// or all of them. - fn detile(&self, tiled: &[u8], changed: Option<&[Range]>) -> bool { + /// A refresh while the runtime is remapping title memory ([`no_wait`]): + /// the texture is read through the kernel, which fails if a page of it + /// is not there at this moment. Then nothing is taken and the texture + /// is looked at again at its next refresh (what was learnt about writes + /// to it is forgotten, so that it is not passed over as unwritten). + /// Returns the bytes read. + fn refresh_unlocked(&self, last: &mut Last, size: usize) -> usize { + use std::sync::atomic::Ordering::Relaxed; + let read = with_read(size, |read| { + if !crate::host::read_into(self.memory, read) { + return false; + } + let hash = blake3::hash(read); + if last.hash != Some(hash) { + last.hash = Some(hash); + self.detile(read); + } + true + }); + if read { + UNLOCKED[0].fetch_add(1, Relaxed); + size + } else { + UNLOCKED[1].fetch_add(1, Relaxed); + last.asked = 0; + 0 + } + } + + /// Detiles `tiled` (the texture's memory) into the staging buffer. + fn detile(&self, tiled: &[u8]) { + self.dirty.store(true, std::sync::atomic::Ordering::Relaxed); #[cfg(feature = "diagnostics")] if tiled.iter().all(|&b| b == 0) { tracing::debug!( @@ -554,118 +843,182 @@ impl Staging { "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" ); } - let mut detiled = false; - for (i, footprint) in self.footprints.iter().enumerate() { - if changed.is_some_and(|c| !overlaps(&self.extents[i], c)) { - continue; - } - let (host_mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); - let mip = host_mip + self.mip_drop; - // SAFETY: the upload buffer is mapped for exactly this range. - let linear = unsafe { std::slice::from_raw_parts_mut(self.data, self.size) }; - if let Err(e) = self.layout.detile( - tiled, - mip, - slice, - &mut linear[footprint.range.clone()], - footprint.placed.Footprint.RowPitch as usize, - footprint.depth_pitch, - ) { + 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); + let f = footprint.Footprint; + let pitch = f.RowPitch as usize; + let len = pitch * rows as usize * f.Depth as usize; + // SAFETY: the subresource's part of the mapped staging buffer. + let linear = unsafe { + std::slice::from_raw_parts_mut(self.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 detiled; + return; } - detiled = true; } - detiled } +} - /// Whether the host texture does not hold the staging buffer's current - /// generation; marks it as recorded when true. - pub(crate) fn take_upload(&self) -> bool { - let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); - if last.uploaded == last.detiled { - return false; - } - last.uploaded = last.detiled; - true +/// Lets go of a title texture's staging buffer (lists that recorded an +/// upload from it hold it until they have run); the next upload makes one +/// anew. +pub(crate) fn unstage(resource: This) { + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() { + map.remove(&(resource as usize)); } +} - /// Records the copy of every staging subresource into `texture` in an - /// open command list whose caller has put the texture in COPY_DEST. - pub(crate) fn record_upload(&self, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource) { - for (i, footprint) in self.footprints.iter().enumerate() { - let to = D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: a borrowed pointer the location never releases. - pResource: unsafe { std::mem::transmute_copy(texture) }, - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: i as u32, - }, - }; - let from = D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: as above. - pResource: unsafe { std::mem::transmute_copy(&self.buffer) }, - Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - PlacedFootprint: footprint.placed, - }, - }; - // SAFETY: an open list; both locations name live resources. - unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; - } - } +/// Where a staged title texture's memory is: address and bytes. +pub(crate) fn staged_memory(resource: This) -> Option<(u64, u64)> { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let (at, len) = map.as_ref()?.get(&(resource as usize))?.memory(); + Some((at as u64, len as u64)) } -#[cfg(test)] -fn detile_plane( - layout: &Layout, - mips: u32, - footprints: &[UploadFootprint], - tiled: &[u8], - linear: &mut [u8], -) -> Result<(), (Error, u32, u32)> { - for (i, footprint) in footprints.iter().enumerate() { - let (mip, slice) = (i as u32 % mips, i as u32 / mips); - let target = - linear - .get_mut(footprint.range.clone()) - .ok_or((Error::TooSmall, mip, slice))?; - layout - .detile( - tiled, - mip, - slice, - target, - footprint.placed.Footprint.RowPitch as usize, - footprint.depth_pitch, - ) - .map_err(|e| (e, mip, slice))?; +/// A fingerprint of the title memory `[at, at + len)`, never 0: of all of +/// it up to 48 KiB, else of 16 KiB at its start, its middle and its end +/// (a texture streams in whole mips; the small ones lie first). Read +/// through the kernel, so pages not there count as zeros. +pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { + const WINDOW: usize = 16 << 10; + thread_local! { + static READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } - Ok(()) + let len = len as usize; + let mut hasher = blake3::Hasher::new(); + READ.with(|read| { + let mut read = read.borrow_mut(); + read.resize(3 * WINDOW, 0); + let mut take = |from: usize, bytes: usize| { + read[..bytes].fill(0); + crate::host::copy_mapped(read.as_mut_ptr(), (at as usize + from) as *const u8, bytes, false); + hasher.update(&read[..bytes]); + }; + if len <= 3 * WINDOW { + take(0, len); + } else { + take(0, WINDOW); + take((len / 2) & !0xfff, WINDOW); + take(len - WINDOW, WINDOW); + } + }); + let hash = hasher.finalize(); + let mut first = [0u8; 8]; + first.copy_from_slice(&hash.as_bytes()[..8]); + u64::from_le_bytes(first) | 1 } -/// Bytes read by a copy and the stride between depth slices. -fn footprint_size(pitch: usize, rows: u32, depth: u32, row_size: usize) -> Option<(usize, usize)> { - if row_size == 0 || row_size > pitch { - return None; - } - let depth_pitch = pitch.checked_mul(rows as usize)?; - // D3D12 allocates the data bytes of the last row only. - let preceding_rows = (rows as usize) - .checked_mul(depth as usize)? - .checked_sub(1)?; - let len = pitch.checked_mul(preceding_rows)?.checked_add(row_size)?; - Some((len, depth_pitch)) +/// Whether a title texture has a staging buffer: a list recorded its +/// upload, and the lists that sample it check it at submission. +/// For the frame listing: whether a list has uploaded `resource`'s staging +/// buffer, and whether it was detiled since. None: it has none. +#[cfg(feature = "diagnostics")] +pub(crate) fn staged_state(resource: This) -> Option<(bool, bool)> { + use std::sync::atomic::Ordering::Relaxed; + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let staging = map.as_ref()?.get(&(resource as usize))?; + Some((staging.uploaded.load(Relaxed), staging.dirty.load(Relaxed))) +} + +pub(crate) fn is_staged(resource: This) -> bool { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize))) +} + +/// The bytes of a title texture's memory, and whether all of it is mapped, +/// if the texture has been staged for upload. +pub(crate) fn staged(resource: This) -> Option<(u64, bool)> { + let s = { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref()?.get(&(resource as usize))?.clone() + }; + let size = s.layout.size as usize; + Some((size as u64, committed(s.memory, size))) } /// Whether `[at, at + len)` is committed memory (streamed textures may be /// unmapped until their pages arrive). pub(crate) fn committed(at: *const u8, len: usize) -> bool { + if by_query() { + return committed_by_query(at, len); + } + if len == 0 { + return true; + } + let (there, of) = readable(at as usize, len, true); + there == of +} + +/// Whether the two questions above and below are put to `VirtualQuery`, as +/// they were (`VICTORY_COMMITTED_QUERY=1`). `VirtualQuery` answers with the +/// length of the run of pages in the same state, which it finds by walking +/// the page tables to the run's end: 8.8 ms for one question in the title's +/// 1.1 GB block (round 6). The pass over the heap's views asks three or +/// more of them for every texture slot that is due, 3,000 slots a frame +/// when the card has no room (run 75): that pass then ran 208-264 ms, and +/// while it ran the submitting thread's write-watch askings waited behind +/// the walks (run 76: 8-22 askings a frame of 6-21 ms each, 46-172 ms). +fn by_query() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_COMMITTED_QUERY").is_some_and(|v| v == "1")) +} + +/// Of the kernel's pages that hold `[at, at + len)` (`len > 0`): how many +/// can be read, and how many there are; with `all`, it stops at the first +/// that cannot. One question to the kernel for up to 256 pages at once +/// (`QueryWorkingSetEx`: the state of each page asked about, no walk); a +/// page not in the working set may still be there (never touched, or +/// trimmed), and a one-byte read through the kernel says. +/// A page that is committed and may not be read counts as not there, which +/// is what the callers ask for: they read or write the memory next. +fn readable(at: usize, len: usize, all: bool) -> (usize, usize) { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const KERNEL_PAGE: usize = 4096; + let (first, last) = (at / KERNEL_PAGE, at.saturating_add(len - 1) / KERNEL_PAGE); + let of = last - first + 1; + let mut there = 0; + // SAFETY: plain data. + let mut info: [PSAPI_WORKING_SET_EX_INFORMATION; 256] = unsafe { std::mem::zeroed() }; + let mut page = first; + while page <= last { + let n = (last - page + 1).min(info.len()); + for (i, entry) in info[..n].iter_mut().enumerate() { + entry.VirtualAddress = ((page + i) * KERNEL_PAGE) as *mut _; + } + // SAFETY: `n` entries of the size given; our own process. + let asked = unsafe { + K32QueryWorkingSetEx( + GetCurrentProcess(), + info.as_mut_ptr().cast(), + (n * size_of::()) as u32, + ) + } != 0; + for (i, entry) in info[..n].iter().enumerate() { + // Bit 0 of the answer: the page is in the working set. + // SAFETY: plain data the query filled in. + let valid = asked && unsafe { entry.VirtualAttributes.Flags } & 1 != 0; + let mut byte = [0u8]; + if valid || crate::host::read_into(((page + i) * KERNEL_PAGE) as *const u8, &mut byte) { + there += 1; + } else if all { + return (there, of); + } + } + page += n; + } + (there, of) +} + +fn committed_by_query(at: *const u8, len: usize) -> bool { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; let mut p = at as usize; - let Some(end) = p.checked_add(len) else { - return false; - }; + let end = p + len; while p < end { // SAFETY: plain data filled in by the query. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; @@ -674,21 +1027,70 @@ pub(crate) fn committed(at: *const u8, len: usize) -> bool { if n == 0 || info.State != MEM_COMMIT { return false; } - let Some(next) = (info.BaseAddress as usize).checked_add(info.RegionSize) else { - return false; - }; - p = next; + p = info.BaseAddress as usize + info.RegionSize; } true } -fn plane_subresources(desc: &D3D12_RESOURCE_DESC) -> u32 { - let mips = u32::from(desc.MipLevels); - if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { - mips - } else { - mips * u32::from(desc.DepthOrArraySize) +/// How many bytes of `[at, at + len)` are committed memory: all of a +/// texture that is there, some of one streaming in (its smaller mips lie +/// at the start of its memory, and their pages are mapped first), none of +/// one not there. With neither the first nor the last page committed the +/// answer is none without a look at the pages between (two queries for the +/// slots whose texture is away, which are asked again and again). +pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; + if len == 0 { + return 0; + } + let start = at as usize; + let end = start.saturating_add(len); + if !committed(at, 1) && !committed((end - 1) as *const u8, 1) { + return 0; + } + if !by_query() { + static BY_PAGE: std::sync::OnceLock = std::sync::OnceLock::new(); + if *BY_PAGE.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_PAGE").is_some_and(|v| v == "1")) { + // By page, without the walk: whole pages, cut to the range. + let (there, _) = readable(start, len, false); + return (there as u64 * 4096).min(len as u64); + } + // By 64 KiB block, one page asked of each: the title's memory is + // mapped in blocks of that size (the console's page), and the + // answer is a measure of how much of a texture has arrived, not a + // promise that every byte can be read (the upload reads through the + // kernel). By page, a texture half there cost a failed kernel read + // for each of its missing pages, every frame it stayed due: 1,663 + // textures "uploaded in part" kept the pass over the heap's views at + // 90-160 ms a frame (run 81). `VICTORY_MAPPED_BY_PAGE=1`: by page. + const BLOCK: usize = 64 << 10; + let mut there = 0u64; + let mut block = start & !(BLOCK - 1); + while block < end { + let (lo, hi) = (block.max(start), block.saturating_add(BLOCK).min(end)); + if readable(lo, 1, true).0 == 1 { + there += (hi - lo) as u64; + } + block = block.saturating_add(BLOCK); + } + return there; + } + let (mut p, mut there) = (start, 0u64); + while p < 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. + let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + let next = (info.BaseAddress as usize).saturating_add(info.RegionSize).min(end); + if n == 0 || next <= p { + break; + } + if info.State == MEM_COMMIT { + there += (next - p) as u64; + } + p = next; } + there } /// The staging state of a title texture, made on first use. @@ -714,13 +1116,13 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { let host = host()?; // SAFETY: a live resource. let d = unsafe { texture.GetDesc() }; - let count = plane_subresources(&d); - if count == 0 { - return None; - } + let count = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + u32::from(d.MipLevels) + } else { + u32::from(d.MipLevels) * u32::from(d.DepthOrArraySize) + }; let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; let mut rows = vec![0u32; count as usize]; - let mut row_sizes = vec![0u64; count as usize]; let mut total = 0; // SAFETY: outputs for `count` subresources. unsafe { @@ -731,19 +1133,10 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { 0, Some(footprints.as_mut_ptr()), Some(rows.as_mut_ptr()), - Some(row_sizes.as_mut_ptr()), + None, Some(&mut total), ); } - let size = usize::try_from(total) - .ok() - .filter(|&size| size <= isize::MAX as usize)?; - let footprints = footprints - .into_iter() - .zip(rows) - .zip(row_sizes) - .map(|((placed, rows), row_size)| UploadFootprint::new(placed, rows, row_size, size)) - .collect::>>()?; let (buffer, data) = host.upload_buffer(total)?; crate::host::name(&buffer, || { format!( @@ -752,354 +1145,135 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { ) }); tracing::debug!(?desc, total, "texture contents uploaded from title memory"); - let mips = u32::from(d.MipLevels).max(1); - let (mip_drop, _) = crate::resource::host_mip_info(resource); - let whole: Vec<_> = std::iter::once(0..layout.size as usize).collect(); - let extents = (0..count) - .map(|i| match layout.extents(i % mips + mip_drop, i / mips) { - Ok(e) => e - .into_iter() - .map(|r| r.start as usize..r.end as usize) - .collect(), - // Detiling it fails too; any change "touches" it. - Err(_) => whole.clone(), - }) - .collect(); + STAGED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + STAGED[1].fetch_add(total, std::sync::atomic::Ordering::Relaxed); let s = Arc::new(Staging { buffer, - size, + #[cfg(feature = "diagnostics")] + size: total, data, footprints, + rows, layout, mips: u32::from(d.MipLevels), - extents, - mip_drop, + bytes: total, memory, last: Mutex::default(), + dirty: std::sync::atomic::AtomicBool::new(true), + uploaded: std::sync::atomic::AtomicBool::new(false), + used: std::sync::atomic::AtomicU64::new(crate::host::moment()), }); map.insert(resource as usize, s.clone()); Some(s) } #[cfg(test)] -// Single ranges in brackets are meant: lists of one range. -#[allow(clippy::single_range_in_vec_init)] -mod tests { - use super::*; - use victory_formats::texture::{Dimension, Swizzle, Texture, TextureDesc}; - use windows::Win32::Graphics::Dxgi::Common::{ - DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC7_UNORM, DXGI_FORMAT_R8_UNORM, - DXGI_FORMAT_R8G8B8A8_UNORM, - }; +mod title_memory_tests { + use super::with_title; + /// Title memory whose tail is reserved and not committed reads through + /// the copy as its bytes and then zeros, without a fault; so does + /// memory a page of which is taken away between two reads, and the + /// zeros are zeros whatever the read buffer held before. #[test] - fn ranges_overlap_only_when_they_share_a_byte() { - let extents = [10..20, 40..50]; - assert!(overlaps(&extents, &[15..16])); - assert!(overlaps(&extents, &[0..5, 49..60])); - assert!(overlaps(&extents, &[0..11])); - // Touching ends share no byte. - assert!(!overlaps(&extents, &[20..40])); - assert!(!overlaps(&extents, &[0..10, 20..40, 50..90])); - assert!(!overlaps(&extents, &[])); - assert!(!overlaps(&[], &[0..100])); - // A long change across several extents, and the reverse. - assert!(overlaps(&[10..20, 40..50], &[0..100])); - assert!(overlaps(&[0..100], &[10..20, 40..50])); - } - - #[test] - fn hashed_pages_that_differ_are_the_change() { - let h = |b: u8| blake3::hash(&[b]); - let (a, b) = ([h(1), h(2), h(3)], [h(1), h(9), h(9)]); - // The last page is short: the memory ends inside it. - assert_eq!( - changed_pages(&a, &b, 64, 150), - Some(vec![64..128, 128..150]) - ); - assert_eq!(changed_pages(&a, &a, 64, 150), Some(vec![])); - // Nothing hashed before: no part known to be unchanged. - assert_eq!(changed_pages(&[], &b, 64, 150), None); - } - - #[test] - fn written_pages_become_ranges_of_the_memory() { - // Memory from 100 for 250 bytes, in 64-byte pages 1..=5. - let r = page_ranges([1, 3, 5].into_iter(), 64, 100, 250); - assert_eq!(r, vec![0..28, 92..156, 220..250]); - // Pages outside the memory give nothing. - assert!(page_ranges([0, 6].into_iter(), 64, 100, 250).is_empty()); - } - - #[test] - fn host_written_clears_after_write_watched_memory_is_written() { - use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, - }; - const MEM_WRITE_WATCH: u32 = 0x20_0000; - let len = crate::watch::PAGE; - // SAFETY: a fresh write-watched allocation, kept (not freed: a reused - // address carries stale watch state into another test's first read). - let ptr = unsafe { - VirtualAlloc( - std::ptr::null(), - len, - MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, - PAGE_READWRITE, - ) - } as *mut u8; - assert!(!ptr.is_null()); - let key = ptr as usize; - // Drain watch state a reused address may carry from a freed - // allocation, so the snapshot below sees a clean slate. - let _ = crate::watch::writes(key, key + len, false); - let state = host_write_state(ptr, len); - assert!(matches!(state, HostWrite::Watched { .. })); - { - let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - map.get_or_insert_with(HashMap::new).insert(key, state); - } - assert!( - still_host_written(key), - "untouched memory stays host-written" - ); - // SAFETY: committed page of ours. - unsafe { ptr.write(0x42) }; - assert!( - !still_host_written(key), - "writing title memory clears host-written state" - ); - assert!(!still_host_written(key)); - forget(key); - } - - #[test] - fn host_written_clears_after_non_watched_memory_changes() { - let mut buf = vec![0x11u8; 256]; - let key = buf.as_ptr() as usize; - let state = host_write_state(buf.as_ptr(), buf.len()); - assert!(matches!(state, HostWrite::Hashed { hash: Some(_), .. })); - { - let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - map.get_or_insert_with(HashMap::new).insert(key, state); + fn an_uncommitted_tail_reads_as_zeros() { + use windows_sys::Win32::System::Memory::*; + const HEAD: usize = 0xb_0000; + const SIZE: usize = 0x20_0000; + // SAFETY: a private reservation of our own; only committed pages + // are written in place, and nothing else reads them in place. + unsafe { + // The read buffer holds something else first. + let other = vec![0x77u8; SIZE]; + with_title(other.as_ptr(), SIZE, |bytes| assert!(bytes.iter().all(|&b| b == 0x77))); + let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!base.is_null()); + assert_eq!(VirtualAlloc(base.cast(), HEAD, MEM_COMMIT, PAGE_READWRITE), base.cast()); + base.write_bytes(0x5a, HEAD); + with_title(base, SIZE, |bytes| { + assert!(bytes[..HEAD].iter().all(|&b| b == 0x5a), "what is mapped"); + assert!(bytes[HEAD..].iter().all(|&b| b == 0), "what is not: zeros"); + }); + // The title takes a page in the middle away: zeros from then + // on, the rest as before. + assert_ne!(VirtualFree(base.add(0x4_0000).cast(), 0x1_0000, MEM_DECOMMIT), 0); + with_title(base, SIZE, |bytes| { + assert!(bytes[..0x4_0000].iter().all(|&b| b == 0x5a)); + assert!(bytes[0x4_0000..0x5_0000].iter().all(|&b| b == 0)); + assert!(bytes[0x5_0000..HEAD].iter().all(|&b| b == 0x5a)); + assert!(bytes[HEAD..].iter().all(|&b| b == 0)); + }); + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); } - assert!(still_host_written(key), "unchanged bytes stay host-written"); - buf[0] = 0x22; - assert!( - !still_host_written(key), - "changed title bytes clear host-written state" - ); - assert!(!still_host_written(key)); - forget(key); } + /// The texture both device-loss runs named last (16 texels wide, 4 or 8 + /// high, format 10, layout 0x100, console flags 0x300000; its memory + /// began 0x300 into a page in run 73 and 0x700 in run 72, and here also + /// 0xf00, so that a page line runs through it): what the detiling is + /// given and what it writes are the same read in place and read through + /// the copy, and the rows it writes end where the staging buffer the + /// host sizes for it ends (896 bytes for 4 rows of 128 bytes 256 apart, + /// 1,920 for 8). #[test] - fn footprint_ends_after_the_last_rows_data() { - // Two depth slices of three rows. The sixth row starts at 1280, - // but only its 20 data bytes belong to the upload range. - assert_eq!(footprint_size(256, 3, 2, 20), Some((1300, 768))); - } - - #[test] - fn footprint_rejects_invalid_geometry_and_out_of_bounds_placement() { - assert_eq!(footprint_size(256, 0, 1, 20), None); - assert_eq!(footprint_size(256, 1, 0, 20), None); - assert_eq!(footprint_size(256, 1, 1, 0), None); - assert_eq!(footprint_size(256, 1, 1, 257), None); - assert_eq!(footprint_size(usize::MAX, 1, 2, 1), None); - - let placed = placed(512, [5, 3, 2]); - let footprint = UploadFootprint::new(placed, 3, 20, 1812).unwrap(); - assert_eq!(footprint.range, 512..1812); - assert!(UploadFootprint::new(placed, 3, 20, 1811).is_none()); - let overflowing = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { - Offset: u64::MAX, - ..placed - }; - assert!(UploadFootprint::new(overflowing, 3, 20, usize::MAX).is_none()); - } - - #[test] - fn plane_zero_counts_each_array_mip_and_each_volume_mip_once() { - let mut desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE1D, - DepthOrArraySize: 6, - MipLevels: 4, - ..Default::default() - }; - assert_eq!(plane_subresources(&desc), 24); - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - assert_eq!(plane_subresources(&desc), 24); - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; - assert_eq!(plane_subresources(&desc), 4); - } - - fn placed(offset: u64, [width, height, depth]: [u32; 3]) -> D3D12_PLACED_SUBRESOURCE_FOOTPRINT { - D3D12_PLACED_SUBRESOURCE_FOOTPRINT { - Offset: offset, - Footprint: D3D12_SUBRESOURCE_FOOTPRINT { - Width: width, - Height: height, - Depth: depth, - RowPitch: 256, - ..Default::default() - }, - } - } - - // Guest mip and slice, host offset and dimensions, then rows and bytes per row. - type Shape = ((u32, u32), u64, [u32; 3], u32, u64); - - fn assert_detiles(desc: TextureDesc, element_bytes: usize, shapes: &[Shape], total: usize) { - let layout = &Texture::new(&desc).unwrap().planes[0].layout; - let mut tiled = vec![0u8; layout.size as usize]; - let mut linear = vec![0xff; total]; - let mut expected = linear.clone(); - let mut footprints = Vec::new(); - for (i, &((mip, slice), offset, dims, rows, row_size)) in shapes.iter().enumerate() { - footprints - .push(UploadFootprint::new(placed(offset, dims), rows, row_size, total).unwrap()); - for z in 0..dims[2] { - for y in 0..rows { - for x in 0..row_size as usize / element_bytes { - let guest = layout.offset(mip, x as u32, y, slice + z).unwrap() as usize; - let host = - offset as usize + (z * rows + y) as usize * 256 + x * element_bytes; - let value = (i * 37 + (z * 7 + y * 13) as usize + x * 3) as u8; - for b in 0..element_bytes { - tiled[guest + b] = value + b as u8; - expected[host + b] = value + b as u8; - } - } + fn the_small_texture_of_runs_72_and_73_detiles_the_same_both_ways() { + use windows_sys::Win32::System::Memory::*; + for (height, within) in [(4u32, 0x300usize), (8, 0x700), (4, 0xf00), (8, 0xf00)] { + // The description as the log printed it, word for word. + let words: [u32; 14] = [3, 0, 0, 0, 16, 0, height, 65537, 10, 1, 0, 256, 3_145_728, 0]; + // SAFETY: fourteen words are a resource description (56 bytes, + // plain numbers). + let desc: crate::resource::ResourceDesc = unsafe { std::mem::transmute(words) }; + let layout = crate::resource::texture_layout(&desc) + .expect("a console layout") + .planes[0] + .layout + .clone(); + let size = layout.size as usize; + let (row, pitch) = (16 * 8, 256usize); + assert!(size >= row * height as usize, "the layout holds every texel"); + // Committed pages and a reserved one after them; the texture + // begins `within` bytes into the first, as the title placed it. + // SAFETY: our own reservation; the committed part is written + // and read in place, by this thread alone. + unsafe { + let pages = size.div_ceil(4096) + 1; + let base = VirtualAlloc(std::ptr::null(), (pages + 1) * 4096, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!base.is_null()); + assert_eq!(VirtualAlloc(base.cast(), pages * 4096, MEM_COMMIT, PAGE_READWRITE), base.cast()); + for i in 0..pages * 4096 { + base.add(i).write((i * 7 + i / 251) as u8); } + let memory = base.add(within); + let in_place = std::slice::from_raw_parts(memory, size); + // The bytes: the same in place and through the copy. + with_title(memory, size, |copied| assert_eq!(copied, in_place)); + // What the detiling writes: the same, and inside the bytes + // the host's staging buffer for this texture has. + let staged = (height as usize - 1) * pitch + row; + assert_eq!(staged, if height == 4 { 896 } else { 1920 }); + let detile = |tiled: &[u8]| { + // The slice `Staging::detile` hands over: whole rows. + let mut linear = vec![0xeeu8; pitch * height as usize]; + layout + .detile(tiled, 0, 0, &mut linear, pitch, pitch * height as usize) + .expect("detiled"); + linear + }; + let direct = detile(in_place); + let through = with_title(memory, size, |copied| detile(copied)); + assert_eq!(direct, through); + for y in 0..height as usize { + assert!(direct[y * pitch..][..row].iter().any(|&b| b != 0xee), "row {y} written"); + assert!(direct[y * pitch + row..(y + 1) * pitch].iter().all(|&b| b == 0xee), "nothing past row {y}"); + } + // A buffer of exactly the staged bytes is enough. + let mut exact = vec![0u8; staged]; + layout + .detile(in_place, 0, 0, &mut exact, pitch, pitch * height as usize) + .expect("the staging buffer's bytes are enough"); + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); } } - detile_plane(layout, desc.mips, &footprints, &tiled, &mut linear).unwrap(); - assert_eq!(linear, expected); - } - - #[test] - fn array_upload_uses_mip_first_order_and_preserves_padding() { - let desc = TextureDesc { - dimension: Dimension::Tex2d, - width: 7, - height: 5, - depth_or_array: 2, - mips: 2, - format: DXGI_FORMAT_R8G8B8A8_UNORM.0 as u32, - samples: 1, - swizzle: Swizzle::SW_4KB_S, - }; - assert_detiles( - desc, - 4, - &[ - ((0, 0), 0, [7, 5, 1], 5, 28), - ((1, 0), 1536, [3, 2, 1], 2, 12), - ((0, 1), 2048, [7, 5, 1], 5, 28), - ((1, 1), 3584, [3, 2, 1], 2, 12), - ], - 3852, - ); - } - - #[test] - fn volume_upload_uses_pitched_depth_slices_and_shrinks_depth_by_mip() { - let desc = TextureDesc { - dimension: Dimension::Tex3d, - width: 5, - height: 3, - depth_or_array: 3, - mips: 2, - format: DXGI_FORMAT_R8_UNORM.0 as u32, - samples: 1, - swizzle: Swizzle::LINEAR, - }; - assert_detiles( - desc, - 1, - &[ - ((0, 0), 0, [5, 3, 3], 3, 5), - ((1, 0), 2560, [2, 1, 1], 1, 2), - ], - 2562, - ); - } - - #[test] - fn block_compressed_upload_uses_whole_blocks_for_partial_rows_and_mips() { - for (format, block_bytes) in [(DXGI_FORMAT_BC1_UNORM, 8), (DXGI_FORMAT_BC7_UNORM, 16)] { - let desc = TextureDesc { - dimension: Dimension::Tex2d, - width: 7, - height: 5, - depth_or_array: 1, - mips: 2, - format: format.0 as u32, - samples: 1, - swizzle: Swizzle::SW_4KB_S, - }; - assert_detiles( - desc, - block_bytes as usize, - &[ - ((0, 0), 0, [8, 8, 1], 2, block_bytes * 2), - ((1, 0), 512, [4, 4, 1], 1, block_bytes), - ], - 512 + block_bytes as usize, - ); - } - } - - #[test] - fn host_writable_flags_exclude_texture_uploads() { - assert!(title_written_flags(D3D12_RESOURCE_FLAG_NONE)); - assert!(title_written_flags( - D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE - )); - for flag in [ - D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, - D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - ] { - assert!(!title_written_flags(flag)); - assert!(!title_written_flags( - flag | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE - )); - } - } - - #[test] - fn committed_rejects_an_address_range_that_wraps() { - assert!(!committed(std::ptr::without_provenance(usize::MAX), 2)); - assert!(committed(std::ptr::without_provenance(usize::MAX), 0)); - assert!(!committed(std::ptr::null(), 1)); - } - - #[test] - fn committed_checks_every_region_in_the_range() { - use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READONLY, PAGE_READWRITE, VirtualAlloc, - VirtualFree, - }; - - // SAFETY: reserve two pages, then commit them separately with - // different protections so VirtualQuery reports distinct regions. - unsafe { - let base = VirtualAlloc(std::ptr::null(), 8192, MEM_RESERVE, PAGE_READWRITE); - assert!(!base.is_null()); - assert_eq!(VirtualAlloc(base, 4096, MEM_COMMIT, PAGE_READWRITE), base); - let bytes = base.cast::(); - assert!(committed(bytes, 4096)); - assert!(!committed(bytes.add(4095), 2)); - let second = bytes.add(4096).cast(); - assert_eq!( - VirtualAlloc(second, 4096, MEM_COMMIT, PAGE_READONLY), - second - ); - assert!(committed(bytes.add(4095), 2)); - assert!(committed(bytes, 8192)); - assert_ne!(VirtualFree(base, 0, MEM_RELEASE), 0); - } } } diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 77043d9..60089a7 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -10,7 +10,9 @@ //! copy leaves each 64 KiB block it took read-only, and our vectored handler //! takes the first write to it: it notes the block as written and gives the //! write access back. The runtime tells us when it maps or unmaps views -//! ([`title_memory_remapped`]), which resets their protection. +//! ([`title_memory_remapped`]), which resets their protection. Blocks found +//! wholly uncommitted are skipped while they remain so; one query can +//! confirm a whole region, including ordinary reservations between views. //! //! shortcut: writes into physical pages through another view (xmem's //! `write_physical`, DirectStorage's page destinations) are not seen at @@ -35,139 +37,262 @@ struct Journal { written: BTreeMap, /// Room for the kernel's answer. found: Vec, - /// Page ranges the kernel was asked about since the submission began - /// (see [`new_submission`]); under Wine only. - asked_now: Vec<(usize, usize)>, + /// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`]) + /// and the asking that did: `writes` answers for a range inside one + /// from the journal, without another kernel call. + ahead: Vec<(usize, usize)>, + ahead_asked: u64, + /// The ahead asking stands for a whole submission ([`ask_once`]): no + /// other ahead asking is made, and `ahead` stays, until + /// [`ask_once_end`]. + kept: bool, } static JOURNAL: Mutex = Mutex::new(Journal { asked: 0, written: BTreeMap::new(), found: Vec::new(), - asked_now: Vec::new(), + ahead: Vec::new(), + ahead_asked: 0, + kept: false, }); -/// Whether we run under Wine (its ntdll exports `wine_get_version`). -fn on_wine() -> bool { - static WINE: std::sync::LazyLock = std::sync::LazyLock::new(|| { - use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; - // SAFETY: plain lookups in ntdll, always loaded. - unsafe { - let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); - !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() +/// Ranges of one submission closer than this are asked about together: +/// walking the pages between them costs less than another kernel call (a +/// call that resets written pages costs 30-70 microseconds whatever the +/// range). +const AHEAD_GAP: usize = (8 << 20) / PAGE; +/// The most one asking covers (its answer needs 8 bytes per 4 KiB page). +const AHEAD_MAX: usize = (1 << 30) / PAGE; + +/// Asks the kernel about many ranges `(start, end)` at once, before the +/// [`writes`] of each: ranges close together are one asking, and `writes` +/// then answers from the journal until [`ask_ahead_done`]. The world's +/// submissions refresh thousands of host copies (6,664 askings a frame, +/// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are +/// left to `writes`. +pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { + let mut pieces: Vec<(usize, usize)> = ranges + .iter() + .filter(|r| r.0 < r.1) + .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE))) + .collect(); + if pieces.len() < 2 { + return; + } + pieces.sort_unstable(); + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let j = &mut *j; + // The submission's one asking stands ([`ask_once`]): what it does not + // hold is left to `writes`. + if j.kept { + return; + } + j.asked += 1; + j.ahead_asked = j.asked; + j.ahead.clear(); + let mut i = 0; + while i < pieces.len() { + let first = pieces[i].0; + let mut last = pieces[i].1; + let mut k = i + 1; + while k < pieces.len() + && pieces[k].0 <= last + AHEAD_GAP + && last.max(pieces[k].1) - first <= AHEAD_MAX + { + last = last.max(pieces[k].1); + k += 1; } - }); - *WINE + ask_run(j, &pieces[i..k]); + i = k; + } } -/// A title allocation as Wine reports it, in [`PAGE`] units. -#[derive(Clone, Copy)] -struct Region { - /// The allocation base, for dropping stale entries. - base: usize, - first: usize, - last: usize, - /// A file view (xmem's physical pages): not write-watched. - mapped: bool, - /// Small enough (4 GiB at most) to be asked about whole. - whole: bool, +/// Since the last frame line: the kernel askings that took a millisecond +/// or more, their microseconds, and the longest asking's. An asking walks +/// page tables, some ten microseconds for most ranges; in run 75 the 2,644 +/// askings of a frame took 219 ms in the lines where the pass over the +/// heap's views ran long, 25-50 ms in the others. These numbers say +/// whether a few askings wait for something or all of them are slow. +#[cfg(feature = "diagnostics")] +static SLOW: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +#[cfg(feature = "diagnostics")] +fn slow(us: u64) { + use std::sync::atomic::Ordering::Relaxed; + if us >= 1000 { + SLOW[0].fetch_add(1, Relaxed); + SLOW[1].fetch_add(us, Relaxed); + } + SLOW[2].fetch_max(us, Relaxed); } -/// The allocation holding `at`, cached by allocation base (walking an -/// allocation's regions under Wine costs one VirtualQuery each). Those -/// above 4 GiB are not asked about whole. -fn allocation(at: usize) -> Option { - use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery}; - let page = at / PAGE; - // Known allocations first: under Wine VirtualQuery takes the same lock - // the title's write faults do. - if let Some((_, &r)) = REGIONS - .lock() - .unwrap_or_else(|e| e.into_inner()) - .range(..=page) - .next_back() - && page < r.last - { - return Some(r); +/// [`SLOW`], taken. +#[cfg(feature = "diagnostics")] +pub(crate) fn slow_asks() -> [u64; 3] { + [0, 1, 2].map(|i| SLOW[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// The submission's refreshes are done: `writes` asks the kernel again. +pub(crate) fn ask_ahead_done() { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if !j.kept { + j.ahead.clear(); } - let query = |p: usize| { - // SAFETY: plain data filled in by the query. - let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - // SAFETY: a valid out pointer of the right size. - let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; - (n != 0).then_some(info) - }; - let info = query(at)?; - let base = info.AllocationBase as usize; - if base == 0 { - return None; +} + +/// Whether a submission asks the kernel once, before its first refresh, +/// about every range its lists refresh (`VICTORY_ASK_ONCE=1`; off by +/// default). +/// +/// A submission's refreshes are done in groups, between the title's own +/// buffer copies (each copy flushes the refreshes recorded before it), and +/// every group asked the kernel again: 2,644 askings a frame, 70 a +/// submission. With the switch the journal answers all of them from one +/// asking made when the submission starts. +/// +/// What changes: memory the title's other threads write while the +/// submission is being prepared is seen by the next submission's asking, +/// not by this one's later groups. What this submission's lists read was +/// written before they were submitted, so before the asking. Our own +/// writes into title memory while preparing are told to the journal +/// ([`wrote`]) or end the asking ([`ask_once_end`]). +pub(crate) fn once() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + // On by default since run 81 (with card buffers: 375-450 ms a frame + // against 573-647, the picture unchanged over four minutes); + // `VICTORY_ASK_ONCE=0` asks per range, as before. + *ON.get_or_init(|| std::env::var_os("VICTORY_ASK_ONCE").is_none_or(|v| v != "0")) +} + +/// With [`once`]: asks about `ranges` (everything a submission's lists +/// refresh) as [`ask_ahead`] does, and lets that asking stand until +/// [`ask_once_end`]. +pub(crate) fn ask_once(ranges: &[(usize, usize)]) { + if !once() { + return; } - // Walk the allocation's regions (Wine splits it by protection, one - // region per run of pages); a long walk stops, and the allocation is - // then only remembered as far as it went, never asked about whole. - let mut end = base; - let mut done = false; - for _ in 0..256 { - let Some(i) = query(end) else { - done = true; - break; - }; - if i.AllocationBase as usize != base { - done = true; - break; + ask_once_end(); + ask_ahead(ranges); + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let j = &mut *j; + if j.ahead.is_empty() { + // `ask_ahead` asked nothing (fewer than two ranges). + j.asked += 1; + j.ahead_asked = j.asked; + } + // `ask_ahead` leaves a range that lies alone to `writes`, which asks + // once per flush: with one asking for the submission that was every + // such range asked again at each of its 70 flushes (run 76: 2,300 + // askings a frame with the switch on, as without it). They are asked + // here, once; what is not write-watched stays with `writes`. + for &(start, end) in ranges { + if start >= end { + continue; + } + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + if !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) && ask_kernel(j, first, last) { + j.ahead.push((first, last)); } - end = i.BaseAddress as usize + i.RegionSize; } - if !done { - // At least past `at`, so the next asking here is a cache hit. - end = end.max((at / PAGE + 1) * PAGE).max(at + (256 << 20)); + j.kept = !j.ahead.is_empty(); +} + +/// The submission's one asking stands no longer: its refreshes are done, +/// or title memory was written in a way the journal was not told. +pub(crate) fn ask_once_end() { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if j.kept { + j.kept = false; + j.ahead.clear(); } - if end <= at { - return None; +} + +/// We wrote title memory `[at, at + len)` while a submission's one asking +/// stands (the title's buffer copies, done at submission): its pages count +/// as written after that asking, so the refreshes that follow copy them. +pub(crate) fn wrote(at: usize, len: usize) { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if !j.kept || len == 0 { + return; } - let r = Region { - base, - first: base.div_ceil(PAGE), - last: end / PAGE, - mapped: info.Type == MEM_MAPPED, - whole: done && end - base <= 4 << 30, - }; - if r.first * PAGE > at || r.last <= r.first { - return None; + j.asked += 1; + let now = j.asked; + for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) { + j.written.insert(page, now); } - let mut regions = REGIONS.lock().unwrap_or_else(|e| e.into_inner()); - // An allocation that replaced older ones in its range. - regions.retain(|_, o| o.last <= r.first || o.first >= r.last); - regions.insert(r.first, r); - Some(r) } -/// Allocations seen by [`allocation`], by first page. Remaps (xmem's views) -/// and failed askings drop entries. -static REGIONS: Mutex> = Mutex::new(BTreeMap::new()); - -fn forget_region(base: usize) { - REGIONS - .lock() - .unwrap_or_else(|e| e.into_inner()) - .retain(|_, r| r.base != base); +/// One kernel asking for `pieces` (page ranges in order); by halves if it +/// fails, as a run across two reservations or into memory that is not +/// write-watched does. A piece alone is left to [`writes`]. +fn ask_run(j: &mut Journal, pieces: &[(usize, usize)]) { + if pieces.len() < 2 { + return; + } + let first = pieces[0].0; + let last = pieces.iter().map(|p| p.1).max().unwrap_or(first); + if ask_kernel(j, first, last) { + j.ahead.push((first, last)); + return; + } + let (a, b) = pieces.split_at(pieces.len() / 2); + ask_run(j, a); + ask_run(j, b); } -/// A submission begins: memory asked about from now on is asked of the -/// kernel again. Within one submission, a range the kernel already -/// answered for is answered from the journal: Wine emulates write watching -/// page by page under one lock (about 1 ms an asking), and the world's -/// copies ask about the same big buffers dozens of times per submission -/// (17 GB checked per frame, 3 s of a frame). A write between two askings -/// in one submission keeps its dirty bit, so the next submission sees it. -pub(crate) fn new_submission() { - if on_wine() { - JOURNAL - .lock() - .unwrap_or_else(|e| e.into_inner()) - .asked_now - .clear(); +/// Asks the kernel for the written pages of pages `[first, last)` and notes +/// them in the journal under the ahead asking; false (and nothing changed) +/// if the range is not write-watched memory of one reservation. +fn ask_kernel(j: &mut Journal, first: usize, last: usize) -> bool { + use windows_sys::Win32::System::Memory::GetWriteWatch; + const WRITE_WATCH_FLAG_RESET: u32 = 1; + let mut count = (last - first) * PAGE / KERNEL_PAGE; + j.found.resize(count.max(j.found.len()), 0); + let mut granularity = 0; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + // SAFETY: the answer buffer holds `count` entries. + let failed = unsafe { + GetWriteWatch( + WRITE_WATCH_FLAG_RESET, + (first * PAGE) as *const _, + (last - first) * PAGE, + j.found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + } != 0; + if failed { + return false; + } + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::Watches, 1); + add(C::WatchUs, started.elapsed().as_micros() as u64); + slow(started.elapsed().as_micros() as u64); + } + let now = j.ahead_asked; + for k in 0..count { + let page = j.found[k] / PAGE; + j.written.insert(page, now); } + true +} + +/// What [`writes`] would say of `[start, end)` from the journal alone, if +/// the range lies in one asked ahead ([`ask_ahead`], [`ask_once`]): the +/// pages written since tracking began and the asking that last found each +/// written, with the number of the asking that stands (as [`writes`] gives +/// it). `None` if the kernel would have to be asked. +pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> { + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + j.ahead + .iter() + .any(|&(a, b)| a <= first && last <= b) + .then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect())) } /// The pages of `[start, end)` (whole pages) as last written, for pages @@ -181,82 +306,44 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let (first, last) = (start / PAGE, end.div_ceil(PAGE)); let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); let j = &mut *j; - if on_wine() && j.asked_now.iter().any(|&(f, l)| f <= first && last <= l) { - j.asked += 1; + // Asked ahead with the submission's other ranges: the journal has it. + if j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { return Some(( - j.asked, + j.ahead_asked, j.written .range(first..last) .map(|(&p, &w)| (p, w)) .collect(), )); } - // Under Wine: view memory cannot be watched (straight to its guards), - // and watched memory is asked about whole allocations at a time, so - // the other buffers in one are answered from the journal for the rest - // of the submission (see `new_submission`). - let region = if on_wine() { allocation(start) } else { None }; - let mapped = region.is_some_and(|r| r.mapped); - let (kfirst, klast) = match region { - Some(r) if !r.mapped && r.whole && r.first <= first && last <= r.last => (r.first, r.last), - _ => (first, last), - }; + let mut count = (last - first) * PAGE / KERNEL_PAGE; + j.found.resize(count.max(j.found.len()), 0); + let mut granularity = 0; #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); - let ask = |kfirst: usize, klast: usize, found: &mut Vec| -> Option { - let mut count = (klast - kfirst) * PAGE / KERNEL_PAGE; - if found.len() < count { - found.resize(count, 0); - } - let mut granularity = 0; - // SAFETY: the answer buffer holds `count` entries. - let ok = unsafe { - GetWriteWatch( - WRITE_WATCH_FLAG_RESET, - (kfirst * PAGE) as *const _, - (klast - kfirst) * PAGE, - found.as_mut_ptr().cast(), - &mut count, - &mut granularity, - ) - } == 0; - ok.then_some(count) - }; - let mut asked = (kfirst, klast); - let mut answer = if mapped { - None - } else { - ask(kfirst, klast, &mut j.found) - }; - if answer.is_none() && !mapped && (kfirst, klast) != (first, last) { - // The allocation was not one watched range after all (or is gone): - // just ours, and look it up again next time. - if let Some(r) = region { - forget_region(r.base); - } - asked = (first, last); - answer = ask(first, last, &mut j.found); - } - let failed = answer.is_none(); - let mut count = answer.unwrap_or(0); + // SAFETY: the answer buffer holds `count` entries. + let failed = unsafe { + GetWriteWatch( + WRITE_WATCH_FLAG_RESET, + (first * PAGE) as *const _, + (last - first) * PAGE, + j.found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + } != 0; let guarded = if failed { count = 0; if !guarded { return None; } - match guard(first * PAGE, last * PAGE, mapped) { - Some(g) => g, - None => { - if let Some(r) = region { - forget_region(r.base); - } - return None; - } - } + #[cfg(feature = "diagnostics")] + let guarding = std::time::Instant::now(); + let written = guard(first * PAGE, last * PAGE); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::GuardUs, guarding.elapsed().as_micros() as u64); + written? } else { - if on_wine() && j.asked_now.len() < 4096 { - j.asked_now.push(asked); - } Vec::new() }; #[cfg(feature = "diagnostics")] @@ -264,6 +351,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve use crate::copystat::{C, add}; add(C::Watches, 1); add(C::WatchUs, started.elapsed().as_micros() as u64); + slow(started.elapsed().as_micros() as u64); } j.asked += 1; let now = j.asked; @@ -271,12 +359,13 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve for page in pages.collect::>() { j.written.insert(page, now); } - let out = j - .written - .range(first..last) - .map(|(&p, &w)| (p, w)) - .collect(); - Some((now, out)) + Some(( + now, + j.written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(), + )) } /// Guarded blocks of view memory. @@ -287,67 +376,75 @@ struct Guards { protected: BTreeSet, /// Of those, the ones not written since a copy took them. clean: BTreeSet, - /// Blocks whose aliases (other views of the same pages) we made - /// read-only, so a write here opens them. - aliased: BTreeSet, + /// Blocks already copied as zeros. While they remain wholly uncommitted, + /// the copy can skip hundreds of MB of failing kernel reads per world frame. + absent: BTreeSet, } static GUARDS: Mutex = Mutex::new(Guards { protected: BTreeSet::new(), clean: BTreeSet::new(), - aliased: BTreeSet::new(), + absent: BTreeSet::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { GUARDS.lock().unwrap_or_else(|e| e.into_inner()) } -/// The runtime's answer to "which other addresses show the physical page -/// mapped at this page address" (the same page in several views). -static ALIAS_LOOKUP: std::sync::OnceLock)> = std::sync::OnceLock::new(); - -/// The runtime tells where else view memory's physical pages show: a write -/// through any of those views is a write to all of them, so guarding a -/// block guards its aliases too, and a write to one opens them all (else a -/// copy of one view keeps what it first took while the title writes the -/// page through another). -pub fn set_alias_lookup(lookup: fn(usize, &mut Vec)) { - let _ = ALIAS_LOOKUP.set(lookup); -} - -/// The blocks showing the same physical memory as `block` (not itself). -fn aliases_of(block: usize, out: &mut Vec) { - out.clear(); - if let Some(lookup) = ALIAS_LOOKUP.get() { - lookup(block * BLOCK, out); - for at in out.iter_mut() { - *at /= BLOCK; - } - out.retain(|&b| b != block); - } -} - /// For view memory: the pages of `[start, end)`'s blocks written since /// they were last guarded (all of a block's pages), guarding them again /// before the caller copies them. `None` if the memory is not a view. -fn guard(start: usize, end: usize, known_mapped: bool) -> Option> { - use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery}; - if !known_mapped { - // 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(start as *const _, &mut info, size_of_val(&info)) }; - if n == 0 || info.Type != MEM_MAPPED { - return None; - } +fn guard(start: usize, end: usize) -> Option> { + // A range whose first block the guards hold already (read-only by our + // hand, or noted absent) is a view: no question to Windows. The + // question walks the page tables to the end of the pages that share the + // first one's state, and a guarded view is one long run of read-only + // pages: 0.6 ms for the title's 174 MB heap, 16 times a frame, and most + // of the 68 ms a frame of "guards" (run 58). + // `VICTORY_GUARD_ASK=1` asks every time, as before. + static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); + let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && { + let g = guards(); + let first = start / BLOCK; + g.protected.contains(&first) || g.absent.contains(&first) + }; + if !known && !is_view(start, end) { + return None; } install(); let mut g = guards(); let mut written = Vec::new(); let mut run: Option = None; let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); + // The range's clean blocks, in order: read off the set in one pass, + // not looked up one block at a time. A frame asks about some 10 GB of + // view memory, 150,000 blocks, nearly all clean: the lookups were most + // of the 60-90 ms a frame of "guards" (run 54). What the loop adds to + // the set meanwhile is the block it stands at or ones before it. + let clean: Vec = g.clean.range(first..last).copied().collect(); + if clean.len() == last - first { + // Nothing written, mapped or new since the range was last taken. + return Some(written); + } + let mut next_clean = 0; + let mut uncommitted_until = first; for block in first..=last { - let open = block < last && !g.clean.contains(&block); + while next_clean < clean.len() && clean[next_clean] < block { + next_clean += 1; + } + let is_clean = next_clean < clean.len() && clean[next_clean] == block; + let mut open = block < last && !is_clean; + if open && g.absent.contains(&block) { + // Ordinary commits need no runtime mapping notification. Reuse + // this asking's query for the following blocks in the same region. + if block >= uncommitted_until { + uncommitted_until = uncommitted_end(block); + } + open = block >= uncommitted_until; + if open { + g.absent.remove(&block); + } + } if open { written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE); if g.protected.contains(&block) { @@ -365,8 +462,53 @@ fn guard(start: usize, end: usize, known_mapped: bool) -> Option> { Some(written) } +/// Whether `[start, end)` is view memory. The title's views lie in +/// placeholders, mapped and unmapped block by block as it streams, so a +/// range can begin in a block that is not mapped right now: the first +/// pages of the range that are there decide. A range with nothing there +/// counts as a view (its blocks are noted absent, and looked at again when +/// the runtime maps them). +/// +/// Looking at the first address only took such a range for "not a view": +/// its copy was marked not watched for good and copied whole at every +/// refresh, around its unmapped pages (run 54: 300 such ranges, 570 MB +/// copied a frame for them, 255 copies a frame reading around holes). +/// `VICTORY_GUARD_HOLES=0` looks at the first address only, as before. +fn is_view(start: usize, end: usize) -> bool { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery, + }; + static HOLES: std::sync::OnceLock = std::sync::OnceLock::new(); + let holes = *HOLES.get_or_init(|| std::env::var_os("VICTORY_GUARD_HOLES").is_none_or(|v| v != "0")); + let mut at = start; + loop { + // 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(at as *const _, &mut info, size_of_val(&info)) }; + if n == 0 { + return false; + } + if info.Type == MEM_MAPPED { + return true; + } + // Committed memory that is no view (the title's heaps, ours), or + // the answer as it was before. + if info.State == MEM_COMMIT || !holes { + return false; + } + // A hole (a placeholder, or free): on to what follows it. + let next = (info.BaseAddress as usize).saturating_add(info.RegionSize); + if next <= at || next >= end { + return true; + } + at = next; + } +} + /// Makes blocks `[from, to)` read-only and notes them guarded and clean; -/// block by block if they span views, leaving out any that fail (unmapped). +/// block by block if they span views, leaving out any that fail, and +/// noting those not committed (unmapped) absent. fn protect(g: &mut Guards, from: usize, to: usize) { use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; let set = |from: usize, to: usize| { @@ -387,29 +529,33 @@ fn protect(g: &mut Guards, from: usize, to: usize) { }; if set(from, to) { note(g, from, to); - } else { - for block in from..to { - if set(block, block + 1) { - note(g, block, block + 1); - } - } + return; } - // Their aliases read-only too, so a write through them faults; not - // clean, though: a copy of an alias has not taken them yet. - let mut others = Vec::new(); for block in from..to { - aliases_of(block, &mut others); - for &other in &others { - if !g.protected.contains(&other) && set(other, other + 1) { - g.protected.insert(other); - } - // Both ways: a write through either opens the other. - g.aliased.insert(block); - g.aliased.insert(other); + if set(block, block + 1) { + note(g, block, block + 1); + } else if block < uncommitted_end(block) { + g.absent.insert(block); } } } +/// The end (exclusive) of the whole uncommitted blocks starting at `block`. +fn uncommitted_end(block: usize) -> usize { + use windows_sys::Win32::System::Memory::{ + MEM_FREE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, VirtualQuery, + }; + // 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((block * BLOCK) as *const _, &mut info, size_of_val(&info)) }; + if n != 0 && matches!(info.State, MEM_RESERVE | MEM_FREE) { + (info.BaseAddress as usize).saturating_add(info.RegionSize) / BLOCK + } else { + block + } +} + /// Gives write access back to the guarded blocks of `[start, end)` and /// notes them written; true if any was guarded. fn open(g: &mut Guards, start: usize, end: usize) -> bool { @@ -419,31 +565,12 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { .range(start / BLOCK..end.div_ceil(BLOCK)) .copied() .collect(); - let unguard = |g: &mut Guards, block: usize| { - g.clean.remove(&block); - if g.protected.remove(&block) { - let mut old = 0; - // SAFETY: a block we made read-only. - unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; - } - }; - // A write here is a write to every view of the same pages. Only blocks - // with guarded aliases are looked up: a write range can be huge. - let aliased: Vec = g - .aliased - .range(start / BLOCK..end.div_ceil(BLOCK)) - .copied() - .collect(); - let mut others = Vec::new(); - for block in aliased { - g.aliased.remove(&block); - aliases_of(block, &mut others); - for &other in &others { - unguard(g, other); - } - } for &block in &blocks { - unguard(g, block); + g.protected.remove(&block); + g.clean.remove(&block); + let mut old = 0; + // SAFETY: a block we made read-only. + unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; } !blocks.is_empty() } @@ -455,28 +582,81 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { pub fn writing(at: usize, len: usize) { // The length is the title's (`fread`'s size times count, saturated). open(&mut guards(), at, at.saturating_add(len)); + // A placed texture there changes with no descriptor written. + crate::descriptor::host::remapped(at, len); +} + +/// Held shared by a read of title memory in place, and alone by the runtime +/// while it changes what title memory shows. +/// +/// The runtime does not change a mapping in one step. To unmap one page of +/// a view it unmaps the whole view and maps what stays again +/// (`xmem.rs` `unmap`), and a view it maps is a reservation until the next +/// call commits it (`map`, then `commit`). For that moment pages the title +/// never gave up are "reserved, never committed", and a thread reading +/// them in place takes an access violation: run 71 in `Layout::detile`, +/// run 74 in the hash before it, both under `Staging::refresh_now`, which +/// had asked whether the texture was all mapped and been told yes. Asking +/// cannot help; not changing the mapping while such a read is under way +/// does. +static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +/// What the runtime holds while it changes what title memory shows +/// ([`title_memory_remapping`]). +pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>); + +/// The runtime is about to map, unmap or move physical pages of title +/// memory: until what it returns is dropped, no read of title memory in +/// place is under way and none begins ([`title_memory_reading`]). Taken +/// around the whole change, the unmapping and the mapping again. +pub fn title_memory_remapping() -> Remapping { + Remapping(MAPPING.write().unwrap_or_else(|e| e.into_inner())) +} + +/// What a read of title memory in place holds ([`title_memory_reading`]). +pub struct Reading(#[allow(dead_code)] std::sync::RwLockReadGuard<'static, ()>); + +/// For reading title memory in place: until what it returns is dropped, +/// the runtime changes no mapping, so memory found mapped stays mapped. +/// Not to be taken twice by one thread, nor held across anything that +/// maps title memory. +pub fn title_memory_reading() -> Reading { + Reading(MAPPING.read().unwrap_or_else(|e| e.into_inner())) +} + +/// [`title_memory_reading`] if it can be had at once: `None` while the +/// runtime changes a mapping (or waits to), for a caller that has another +/// way to read and would rather not wait. +pub fn title_memory_reading_now() -> Option { + match MAPPING.try_read() { + Ok(guard) => Some(Reading(guard)), + Err(std::sync::TryLockError::Poisoned(e)) => Some(Reading(e.into_inner())), + Err(std::sync::TryLockError::WouldBlock) => None, + } } /// The runtime mapped or unmapped title memory `[at, at + len)`: what it -/// shows is new and read-write, so it is no longer guarded. +/// shows is new and read-write, so it is no longer guarded (nor known +/// unmapped). pub fn title_memory_remapped(at: usize, len: usize) { - REGIONS.lock().unwrap_or_else(|e| e.into_inner()).clear(); + // A placed texture there arrives, goes or changes with no descriptor + // written. + crate::descriptor::host::remapped(at, len); + // The views the runtime told us of there are no longer what it shows. + crate::inplace::views_gone(at, len); + // And nothing stays in place over it. + crate::inplace::title_memory_freeing(at, len); let mut g = guards(); - let blocks: Vec = g - .protected - .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) - .copied() - .collect(); + let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK); + let absent: Vec = g.absent.range(range.clone()).copied().collect(); + for block in absent { + g.absent.remove(&block); + } + let blocks: Vec = g.protected.range(range).copied().collect(); for block in blocks { g.protected.remove(&block); g.clean.remove(&block); } - let first = at / BLOCK; - let end = at.saturating_add(len).div_ceil(BLOCK); - let aliased: Vec = g.aliased.range(first..end).copied().collect(); - for block in aliased { - g.aliased.remove(&block); - } } /// Registers the handler that takes writes to guarded blocks, once, ahead @@ -536,7 +716,7 @@ fn writable(at: usize) -> bool { mod tests { use super::*; use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, }; const MEM_WRITE_WATCH: u32 = 0x20_0000; @@ -553,16 +733,10 @@ mod tests { } as usize; assert_ne!(p, 0); let (start, end) = (p, p + 4 * PAGE); - // A reused address can carry stale watch state (kernel bits, journal - // entries) left by a freed allocation: drain it, then ask fresh. - let _ = writes(start, end, false); - new_submission(); let (_, before) = writes(start, end, false).expect("watched"); assert!(before.is_empty()); // SAFETY: committed pages of ours. unsafe { ((p + PAGE + 8) as *mut u8).write(1) }; - // Under Wine a range is asked of the kernel once per submission. - new_submission(); let (now, after) = writes(start, end, false).expect("watched"); assert_eq!(after, [(p / PAGE + 1, now)]); // Another asker after the kernel's bit was cleared still sees it. @@ -578,46 +752,8 @@ mod tests { ) .is_none() ); - // Kept, not freed: another test given this address would see its - // watch state as its own first read (the kernel's bits and the - // journal's entries outlive the allocation they were made for). - } - - /// Under Wine, a write after a range was asked about in a submission - /// is reported in the next one, not lost. - #[test] - fn writes_within_a_submission_show_in_the_next() { - if !on_wine() { - return; - } - // SAFETY: a fresh write-watched allocation, freed at the end. - let p = unsafe { - VirtualAlloc( - std::ptr::null(), - 2 * PAGE, - MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, - PAGE_READWRITE, - ) - } as usize; - assert_ne!(p, 0); - // Kept, not freed: another test given this address would see the - // journal's entries for it. The journal may already hold some (a - // freed allocation of another test here), so compare with them. - new_submission(); - let (_, before) = writes(p, p + 2 * PAGE, false).expect("watched"); - // SAFETY: committed pages of ours. - unsafe { ((p + 8) as *mut u8).write(1) }; - let (_, same) = writes(p, p + 2 * PAGE, false).expect("watched"); - assert_eq!( - same, before, - "answered from the journal within the submission" - ); - new_submission(); - let (now, next) = writes(p, p + 2 * PAGE, false).expect("watched"); - assert!( - next.contains(&(p / PAGE, now)), - "the write shows in the next submission" - ); + // SAFETY: our allocation. + unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; } /// A kernel read into a guarded view block fails; opened first, it @@ -642,7 +778,7 @@ mod tests { MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize }; assert_ne!(view, 0); - assert!(guard(view, view + 2 * BLOCK, false).is_some()); // now read-only + assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only let mut file = tempfile::tempfile().unwrap(); file.write_all(b"from the disk").unwrap(); // `ReadFile` inside: the kernel writes the view. @@ -658,13 +794,11 @@ mod tests { ); writing(view + 100, 13); assert!(read(&mut file)); + // SAFETY: the bytes just read. + let landed = unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }; + assert_eq!(landed, b"from the disk"); assert_eq!( - // SAFETY: the bytes just read. - unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, - b"from the disk" - ); - assert_eq!( - guard(view, view + 2 * BLOCK, false), + guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()) ); // SAFETY: our view. @@ -678,78 +812,297 @@ mod tests { title_memory_remapped(view, 2 * BLOCK); } - /// A write or mapping that runs past the end of the address space (a - /// title's `fread` with a huge count) covers up to the end; the sum used - /// to overflow. Up there no test has guarded blocks. #[test] - fn ranges_past_the_address_space_end_do_not_overflow() { - let top = usize::MAX - 16; - writing(top, PAGE); - title_memory_remapped(top, usize::MAX); + fn writes_in_partly_committed_view_blocks_are_reported() { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, + SEC_RESERVE, UnmapViewOfFile, + }; + + const SIZE: usize = 3 * BLOCK; + struct View(MEMORY_MAPPED_VIEW_ADDRESS); + impl Drop for View { + fn drop(&mut self) { + title_memory_remapped(self.0.Value as usize, SIZE); + // SAFETY: our view is still mapped. + unsafe { UnmapViewOfFile(self.0) }; + } + } + // SAFETY: a new reserved pagefile section. The view holds its own + // reference after we close the handle, including on assertion failure. + let view = unsafe { + let section = CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE | SEC_RESERVE, + 0, + SIZE as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, SIZE); + CloseHandle(section); + assert!(!view.Value.is_null()); + View(view) + }; + let start = view.0.Value as usize; + let commit = |at: usize, len| { + // SAFETY: these pages belong to our reserved view. + let committed = unsafe { VirtualAlloc(at as _, len, MEM_COMMIT, PAGE_READWRITE) }; + assert_eq!(committed as usize, at); + }; + let early = start + BLOCK + 3 * KERNEL_PAGE; + let late = start + 2 * BLOCK + 3 * KERNEL_PAGE; + commit(start, BLOCK); + commit(early, KERNEL_PAGE); + let refresh = || guard(start, start + SIZE).unwrap(); + assert_eq!(refresh(), [start / PAGE, early / PAGE, late / PAGE]); + // The last block is still entirely reserved. + assert!(!refresh().contains(&(late / PAGE))); + + commit(late, KERNEL_PAGE); // Ordinary commit, without a runtime mapping notification. + for at in [early, late] { + assert!(writable(at)); + // SAFETY: each address is inside its committed read-write page. + unsafe { (at as *mut u8).write_volatile(1) }; + } + assert_eq!(refresh(), [early / PAGE, late / PAGE]); } + /// A range of view memory whose first block is not mapped is a view + /// all the same: its blocks are reported once, then the ones written + /// or mapped since. #[test] - fn a_write_through_an_alias_view_is_seen_by_a_guard_on_the_other() { - use std::sync::atomic::{AtomicUsize, Ordering}; + fn a_range_that_begins_in_an_unmapped_block_is_guarded() { use windows_sys::Win32::System::Memory::{ - CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, - UnmapViewOfFile, + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, + MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2, + VirtualAlloc2, }; - static A: AtomicUsize = AtomicUsize::new(0); - static B: AtomicUsize = AtomicUsize::new(0); - fn lookup(at: usize, out: &mut Vec) { - let (a, b) = (A.load(Ordering::Relaxed), B.load(Ordering::Relaxed)); - let page = at - at % BLOCK; - if page == a { - out.push(b); - } else if page == b { - out.push(a); + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder of three blocks and a pagefile + // section of three; the middle block is mapped first. + let (p, section) = unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + 3 * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (3 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + (p, section) + }; + let map = |block: usize| { + // SAFETY: splits the placeholder at the block and maps the + // section's block there. + let view = unsafe { + VirtualFree( + (p + block * BLOCK) as *mut _, + BLOCK, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + section, + GetCurrentProcess(), + (p + block * BLOCK) as *const _, + (block * BLOCK) as u64, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p + block * BLOCK); + view + }; + let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; + let all: Vec = (0..3).flat_map(pages).collect(); + // Nothing mapped at all: a view with every block absent. + assert!(is_view(p, p + 3 * BLOCK)); + let middle = map(1); + title_memory_remapped(p + BLOCK, BLOCK); + // The range begins in the placeholder, its middle block is a view. + assert!(is_view(p, p + 3 * BLOCK)); + assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()), "nothing written since"); + // SAFETY: inside the mapped middle block. + unsafe { ((p + BLOCK + 8) as *mut u8).write_volatile(1) }; + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); + let first = map(0); + title_memory_remapped(p, BLOCK); + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(0).collect())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + // Memory of ours that is no view stays none. + let mut local = [0u8; 16]; + let at = local.as_mut_ptr() as usize; + assert!(!is_view(at, at + local.len())); + // SAFETY: our views and placeholder. + unsafe { + UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); + UnmapViewOfFile2(GetCurrentProcess(), middle, MEM_PRESERVE_PLACEHOLDER); + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); } + windows_sys::Win32::Foundation::CloseHandle(section); } - // SAFETY: one pagefile section of a block, mapped twice read-write. - let (a, b) = unsafe { + title_memory_remapped(p, 3 * BLOCK); + } + + /// Blocks of a placeholder between views are reported once, then not + /// again (they cannot be guarded) until the runtime maps them. + #[test] + fn unmapped_blocks_are_reported_once_until_mapped() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, + MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2, + VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder of three blocks and a pagefile + // section of two; block 0 shows the section's first block, as the + // runtime maps physical pages. + let (p, section) = unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + 3 * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); let section = CreateFileMappingW( -1isize as _, std::ptr::null(), PAGE_READWRITE, 0, - BLOCK as u32, + (2 * BLOCK) as u32, std::ptr::null(), ); assert!(!section.is_null()); - ( - MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, BLOCK).Value as usize, - MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, BLOCK).Value as usize, - ) + (p, section) }; - assert!(a != 0 && b != 0 && a % BLOCK == 0 && b % BLOCK == 0); - A.store(a, Ordering::Relaxed); - B.store(b, Ordering::Relaxed); - set_alias_lookup(lookup); - // A copy of view `a` takes the block and guards it (and `b`). - assert_eq!(guard(a, a + BLOCK, true), Some(vec![a / PAGE])); - assert_eq!(guard(a, a + BLOCK, true), Some(vec![]), "clean"); - // The title writes the page through `b`: `a` shows it written. - // SAFETY: our view; the guard's handler opens it. - unsafe { ((b + 8) as *mut u8).write_volatile(7) }; - // SAFETY: the same byte through the other view. - assert_eq!(unsafe { ((a + 8) as *const u8).read_volatile() }, 7); + let map = |block: usize| { + // SAFETY: splits the placeholder at the block and maps the + // section's block there. + let view = unsafe { + VirtualFree( + (p + block * BLOCK) as *mut _, + BLOCK, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + section, + GetCurrentProcess(), + (p + block * BLOCK) as *const _, + (block * BLOCK) as u64, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p + block * BLOCK); + view + }; + let first = map(0); + let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; + let all: Vec = (0..3).flat_map(pages).collect(); + assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); assert_eq!( - guard(a, a + BLOCK, true), - Some(vec![a / PAGE]), - "written through the alias" + guard(p, p + 3 * BLOCK), + Some(Vec::new()), + "nothing written since" ); - // And the other way round: a kernel write into `a` opens `b`. - assert_eq!(guard(b, b + BLOCK, true), Some(vec![b / PAGE])); - assert_eq!(guard(b, b + BLOCK, true), Some(vec![])); - writing(a + 16, 4); - assert_eq!(guard(b, b + BLOCK, true), Some(vec![b / PAGE])); - A.store(0, Ordering::Relaxed); - B.store(0, Ordering::Relaxed); - for v in [a, b] { - // SAFETY: our views. - unsafe { UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: v as *mut _ }) }; - title_memory_remapped(v, BLOCK); + let second = map(1); + title_memory_remapped(p + BLOCK, BLOCK); + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + // SAFETY: our views and placeholder. + unsafe { + UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); + UnmapViewOfFile2(GetCurrentProcess(), second, MEM_PRESERVE_PLACEHOLDER); + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + windows_sys::Win32::Foundation::CloseHandle(section); } + title_memory_remapped(p, 3 * BLOCK); + } + + /// A write or mapping that runs past the end of the address space (a + /// title's `fread` with a huge count) covers up to the end; the sum used + /// to overflow. Up there no test has guarded blocks. + #[test] + fn ranges_past_the_address_space_end_do_not_overflow() { + let top = usize::MAX - 16; + writing(top, PAGE); + title_memory_remapped(top, usize::MAX); + } +} + +#[cfg(test)] +mod mapping_tests { + use super::{title_memory_reading, title_memory_remapping}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, mpsc}; + use std::time::Duration; + + /// A change of mapping waits for a read in place that is under way, and + /// a read in place waits for a change of mapping. + #[test] + fn reads_in_place_and_remappings_wait_for_each_other() { + // A reader holds; the change does not begin until it lets go. + let changed = Arc::new(AtomicBool::new(false)); + let reading = title_memory_reading(); + let (began, wait) = mpsc::channel(); + let change = { + let changed = changed.clone(); + std::thread::spawn(move || { + began.send(()).unwrap(); + let _changing = title_memory_remapping(); + changed.store(true, Ordering::SeqCst); + }) + }; + wait.recv().unwrap(); + std::thread::sleep(Duration::from_millis(100)); + assert!(!changed.load(Ordering::SeqCst), "the mapping changed under a read in place"); + drop(reading); + change.join().unwrap(); + assert!(changed.load(Ordering::SeqCst)); + // A change holds; the read does not begin until it is done. + let read = Arc::new(AtomicBool::new(false)); + let changing = title_memory_remapping(); + let (began, wait) = mpsc::channel(); + let reader = { + let read = read.clone(); + std::thread::spawn(move || { + began.send(()).unwrap(); + let _reading = title_memory_reading(); + read.store(true, Ordering::SeqCst); + }) + }; + wait.recv().unwrap(); + std::thread::sleep(Duration::from_millis(100)); + assert!(!read.load(Ordering::SeqCst), "a read in place began during a change of mapping"); + drop(changing); + reader.join().unwrap(); + assert!(read.load(Ordering::SeqCst)); } } diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index e8d6baf..a2fa943 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -13,7 +13,7 @@ victory-loader.workspace = true victory-pe.workspace = true victory-formats.workspace = true opus-pure.workspace = true -miniz_oxide.workspace = true +zlib-rs.workspace = true tracing.workspace = true [target.'cfg(windows)'.dependencies] diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs index 6cb7d4d..8a2a875 100644 --- a/crates/victory-hle/src/host.rs +++ b/crates/victory-hle/src/host.rs @@ -84,7 +84,6 @@ impl HostPolicy { /// The host's own `name` from the System32 DLL `dll`: what a title import /// of it is bound to when we do not override it. -#[cfg(windows)] pub(crate) fn function(dll: &str, name: &str) -> Option { let name = ImportSymbol::Name { hint: 0, diff --git a/crates/victory-hle/src/modules/apu.rs b/crates/victory-hle/src/modules/apu.rs index 9027da0..0668f0d 100644 --- a/crates/victory-hle/src/modules/apu.rs +++ b/crates/victory-hle/src/modules/apu.rs @@ -181,13 +181,7 @@ pub extern "system" fn XApuConnect( } let event = if input.options & RESULT_EVENT != 0 { // SAFETY: plain auto-reset event, no name. - let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }; - if event.is_null() { - // SAFETY: allocated above with `layout`. - unsafe { std::alloc::dealloc(memory, layout) }; - return E_OUTOFMEMORY; - } - event + unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) } } else { std::ptr::null_mut() }; @@ -277,15 +271,13 @@ pub extern "system" fn XApuEnqueueCommand( tracing::debug!(stream, channels, "Opus stream activated"); result.error = if decoder.is_some() { ALREADY_ACTIVE - } else if !(1..=2).contains(&channels) { - E_INVALIDARG } else { match OpusDecoder::new(48_000, channels as usize) { - Ok(d) => { + Ok(d) if (1..=2).contains(&channels) => { *decoder = Some(d); S_OK } - Err(_) => E_INVALIDARG, + _ => E_INVALIDARG, } }; } @@ -348,27 +340,17 @@ fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: & .min(command.frame_count as usize) .min(output_length as usize / (4 * channels)); let kept = &pcm[first * channels..(first + frames) * channels]; - let bytes = frames * channels * 4; - if bytes > 0 { - // SAFETY: `output` is non-null and holds at least `bytes <= output_length` bytes; - // writing raw bytes avoids requiring 4-byte alignment on the title's `*mut u8`. - let out = unsafe { std::slice::from_raw_parts_mut(output, bytes) }; - if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 { - let (left, right) = out.split_at_mut(frames * 4); - let (left, _) = left.as_chunks_mut::<4>(); - let (right, _) = right.as_chunks_mut::<4>(); - for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() { - left[i] = frame[0].to_le_bytes(); - right[i] = frame[1].to_le_bytes(); - } - } else { - for (dst, &sample) in out.as_chunks_mut::<4>().0.iter_mut().zip(kept) { - *dst = sample.to_le_bytes(); - } + // SAFETY: the title's output buffer holds `output_length` bytes. + let out = unsafe { std::slice::from_raw_parts_mut(output.cast::(), frames * channels) }; + if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 { + for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() { + (out[i], out[frames + i]) = (frame[0], frame[1]); } + } else { + out.copy_from_slice(kept); } result.frames = frames as u32; - result.output_length = bytes as u32; + result.output_length = (frames * channels * 4) as u32; } pub extern "system" fn XApuDequeueResult(handle: *mut Connection, out: *mut ApuResult) -> HRESULT { @@ -539,140 +521,4 @@ mod tests { assert_eq!(error, INVALID_STREAM); assert_eq!(XApuDisconnect(handle), S_OK); } - - #[test] - fn decodes_into_unaligned_output_interleaved_and_deinterleaved() { - let tone: Vec = (0..960 * 2) - .map(|i| { - let phase = (i / 2) as f32 * std::f32::consts::TAU / 48_000.0; - if i % 2 == 0 { - (phase * 440.0).sin() * 0.5 - } else { - (phase * 880.0).sin() * 0.25 - } - }) - .collect(); - let mut encoder = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); - let mut packet = [0u8; 1500]; - let n = encoder.encode(&tone, 960, &mut packet).unwrap(); - - for (options, deinterleaved) in [(0u32, false), (DEINTERLEAVED_OUTPUT, true)] { - let input = ConnectInput { - process: DECODE_OPUS, - streams: 4, - commands_per_stream: 4, - memory: 0x4_0000, - frames_per_output: 0, - options, - }; - let mut output = ConnectOutput { - memory: std::ptr::null_mut(), - result_event: std::ptr::null_mut(), - }; - let mut handle = std::ptr::null_mut(); - assert_eq!(XApuConnect(&input, &mut output, &mut handle), S_OK); - let base = output.memory.cast::(); - - // Invalid channel counts fail cleanly without activating the stream. - for bad_channels in [0u32, 3, u32::MAX] { - let bad = Activate { - id: id(ACTIVATE, 0), - channels: bad_channels, - init_length: 0, - init: std::ptr::null(), - start_pitch: 1.0, - processing_length: 0, - processing: std::ptr::null_mut(), - }; - assert_eq!( - XApuEnqueueCommand(handle, (&raw const bad).cast(), std::ptr::null_mut()), - S_OK - ); - let mut res = std::mem::MaybeUninit::::zeroed(); - assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); - // SAFETY: written by `XApuDequeueResult`. - let err = unsafe { res.assume_init() }.error; - assert_eq!(err, E_INVALIDARG, "channels={bad_channels}"); - } - - // Activate two identical stereo decoders so aligned and unaligned outputs match bit-for-bit. - for stream in [0u32, 1] { - let activate = Activate { - id: id(ACTIVATE, stream), - channels: 2, - init_length: 0, - init: std::ptr::null(), - start_pitch: 1.0, - processing_length: 0, - processing: std::ptr::null_mut(), - }; - assert_eq!( - XApuEnqueueCommand(handle, (&raw const activate).cast(), std::ptr::null_mut()), - S_OK - ); - let mut res = std::mem::MaybeUninit::::zeroed(); - assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); - // SAFETY: written by `XApuDequeueResult`. - let err = unsafe { res.assume_init() }.error; - assert_eq!(err, S_OK); - } - - // SAFETY: inside the connection memory. - unsafe { std::ptr::copy_nonoverlapping(packet.as_ptr(), base, n) }; - let aligned_out = base.wrapping_add(0x10000); - let unaligned_out = base.wrapping_add(0x20001); // 1 mod 4: misaligned for f32 - - for (stream, out_ptr, frame_count) in [ - (0u32, aligned_out, 960u32), - (1u32, unaligned_out, 960u32), - (1u32, base.wrapping_add(0x30003), 0u32), // zero frames at misaligned ptr - ] { - let proc_cmd = Process { - id: id(PROCESS, stream), - pitch_ramp: 0.0, - target_pitch: 1.0, - first_frame: 0, - frame_count, - input_length: n as u32, - input: base, - output_length: 960 * 8, - output: out_ptr, - }; - assert_eq!( - XApuEnqueueCommand(handle, (&raw const proc_cmd).cast(), std::ptr::null_mut()), - S_OK - ); - let mut res = std::mem::MaybeUninit::::zeroed(); - assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); - // SAFETY: written by `XApuDequeueResult`. - let decoded = unsafe { res.assume_init() }; - let (err, frames, len) = (decoded.error, decoded.frames, decoded.output_length); - assert_eq!((err, frames, len), (S_OK, frame_count, frame_count * 8)); - } - - // SAFETY: both output regions are inside connection memory and hold 960 * 8 bytes. - let (aligned_bytes, unaligned_bytes) = unsafe { - ( - std::slice::from_raw_parts(aligned_out, 960 * 8), - std::slice::from_raw_parts(unaligned_out, 960 * 8), - ) - }; - assert_eq!( - unaligned_bytes, aligned_bytes, - "unaligned output must match aligned output (deinterleaved={deinterleaved})" - ); - let samples: Vec = unaligned_bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| f32::from_le_bytes(*c)) - .collect(); - let energy: f32 = samples.iter().map(|s| s * s).sum::() / samples.len() as f32; - assert!( - energy > 0.01, - "expected decoded tone (deinterleaved={deinterleaved}), energy={energy}" - ); - assert_eq!(XApuDisconnect(handle), S_OK); - } - } } diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 2bdfae1..5ce7551 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -12,7 +12,7 @@ //! Mixed audio leaves through the host's WASAPI, which titles and //! middleware reach through COM like on PC. fmod's console build sets up //! the coprocessor inside `System_Create` and waits there for its first -//! command to be acknowledged; Grand Theft Auto VI uses only XMA contexts. +//! command to be acknowledged; the title uses only XMA contexts. #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] @@ -114,6 +114,11 @@ fn heap_alloc(size: usize, align: usize) -> Option<(*mut u8, u32)> { heap.blocks .insert(ptr as usize, Block { size, apu, layout }); heap.by_apu.insert(apu, ptr as usize); + // The big ones are named in the log: they are the title's audio memory + // given out of our allocator, which the memory line counts as ours. + if size >= 32 << 20 { + tracing::info!(mb = size >> 20, at = ?ptr, "audio memory for the title from our allocator"); + } Some((ptr, apu)) } @@ -492,10 +497,9 @@ impl Xma { let start = Instant::now(); let mut active = 0; for index in 0..self.voices.len() as u32 { - if let (Some(context), Some(voice)) = ( - self.context(index), - &mut *lock(&self.voices[index as usize]), - ) { + if let (Some(context), Some(voice)) = + (self.context(index), &mut *lock(&self.voices[index as usize])) + { pump(context, voice); active += 1; } @@ -644,10 +648,7 @@ fn dump_input(index: u32, context: Context) { ); let _ = std::fs::create_dir_all(&dir); let _ = std::fs::write(dir.join(format!("{n:02}-{index}.ctx")), words); - let _ = std::fs::write( - dir.join(format!("{n:02}-{index}.xma")), - input.unwrap_or_default(), - ); + let _ = std::fs::write(dir.join(format!("{n:02}-{index}.xma")), input.unwrap_or_default()); } /// Starts the decoding thread on the first enabled voice, and has it fill diff --git a/crates/victory-hle/src/modules/audio/capture.rs b/crates/victory-hle/src/modules/audio/capture.rs index 4392204..f39bb3d 100644 --- a/crates/victory-hle/src/modules/audio/capture.rs +++ b/crates/victory-hle/src/modules/audio/capture.rs @@ -12,7 +12,6 @@ use std::io::{Seek, SeekFrom, Write}; use std::path::Path; use std::time::{Duration, Instant}; -use windows::Win32::Foundation::WAIT_OBJECT_0; use windows::Win32::Media::Audio::{ AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_LOOPBACK, @@ -24,6 +23,7 @@ use windows::Win32::Media::Audio::{ VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVE_FORMAT_PCM, WAVEFORMATEX, }; use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx}; +use windows::Win32::Foundation::WAIT_OBJECT_0; use windows::Win32::System::Threading::{ OpenProcess, PROCESS_SYNCHRONIZE, Sleep, WaitForSingleObject, }; diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index 96491f0..23bbccf 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -17,12 +17,10 @@ extern "system" fn create_device( iid: *const Iid, out: *mut *const Object, ) -> HRESULT { + victory_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree); + victory_gpu::resource::use_page_mapper(super::xmem::map_alias); #[cfg(windows)] - { - victory_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree); - victory_gpu::resource::use_page_mapper(super::xmem::map_alias); - victory_gpu::on_failure(host_gpu_failed); - } + victory_gpu::on_failure(host_gpu_failed); device::create(adapter, parameters, iid, out) } @@ -91,112 +89,20 @@ mod tests { use super::*; use crate::{HleResolver, HostPolicy}; use victory_loader::ImportResolver; - use victory_loader::Provenance; use victory_loader::Resolution; use victory_pe::ImportSymbol; - fn symbol(name: &str) -> ImportSymbol { - ImportSymbol::Name { - hint: 0, - name: name.into(), - } - } - #[test] fn the_interface_id_import_is_bound_to_data() { + let symbol = ImportSymbol::Name { + hint: 0, + name: "IID_ID3D12Device".into(), + }; let r = HleResolver::new(HostPolicy::none()); - let Resolution::Found { address, .. } = - r.resolve("d3d12_xs.dll", &symbol("IID_ID3D12Device")) - else { + let Resolution::Found { address, .. } = r.resolve("d3d12_xs.dll", &symbol) else { panic!("not bound"); }; // SAFETY: the address is our static id. assert_eq!(unsafe { *(address as *const [u8; 16]) }, device::IID); } - - #[test] - fn module_serves_the_console_d3d12_dll() { - let m = module(); - assert_eq!(m.name, "d3d12x"); - assert!(m.serves("d3d12_xs.dll")); - assert!(m.serves("D3D12_XS.DLL"), "DLL names are case-insensitive"); - assert!(!m.serves("d3d12.dll")); - assert!(!m.serves("dxgi.dll")); - } - - #[test] - fn exports_are_the_console_entry_points() { - let m = module(); - let mut names: Vec<&str> = m.exports.iter().map(|e| e.name).collect(); - names.sort_unstable(); - let mut expected = [ - "D3D12ConfigureVirtualMemoryX", - "D3D12CreateRootSignatureDeserializer", - "D3D12SerializeRootSignature", - "D3D12SerializeVersionedRootSignature", - "D3D12XboxCreateDevice", - "IID_ID3D12Device", - ]; - expected.sort_unstable(); - assert_eq!(names, expected, "exactly the console's entry points"); - for export in &m.exports { - assert_ne!(export.address, 0, "{} has no address", export.name); - } - } - - #[test] - fn every_export_resolves_as_hle_from_the_dll() { - let resolver = HleResolver::new(HostPolicy::none()); - for export in module().exports { - match resolver.resolve("d3d12_xs.dll", &symbol(export.name)) { - Resolution::Found { - address, - provenance, - } => { - assert_eq!(provenance, Provenance::Hle, "{}", export.name); - assert_eq!(address, export.address, "{}", export.name); - } - Resolution::Missing => panic!("{} is not bound", export.name), - } - } - } - - #[test] - fn the_interface_id_export_points_at_the_device_iid() { - let export = module() - .exports - .into_iter() - .find(|e| e.name == "IID_ID3D12Device") - .expect("the interface id is exported as data"); - assert_eq!(export.address, (&raw const device::IID) as usize); - // SAFETY: the export is the address of our static interface id. - assert_eq!(unsafe { *(export.address as *const [u8; 16]) }, device::IID); - } - - #[test] - fn device_creation_rejects_null_arguments() { - // E_INVALIDARG, the host's error for a missing argument. - const E_INVALIDARG: i32 = 0x8007_0057u32 as i32; - let version: u32 = 0x0002_0004; - // No device parameters. - assert_eq!( - create_device( - std::ptr::null(), - std::ptr::null(), - &device::IID, - std::ptr::null_mut(), - ), - E_INVALIDARG - ); - // No interface id. - assert_eq!( - create_device( - std::ptr::null(), - &version, - std::ptr::null(), - std::ptr::null_mut(), - ), - E_INVALIDARG - ); - } } diff --git a/crates/victory-hle/src/modules/display.rs b/crates/victory-hle/src/modules/display.rs index b5777b7..fd13187 100644 --- a/crates/victory-hle/src/modules/display.rs +++ b/crates/victory-hle/src/modules/display.rs @@ -5,7 +5,7 @@ use std::ffi::{c_char, c_void}; use super::xgameruntime::{ - Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, add_ref, missing, text, + Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, add_ref, missing, put, text, }; /// HDR mode; asked for with this interface id since 2020. @@ -36,7 +36,7 @@ pub const CAPTURE_PROVIDER: Guid = Guid::new( 0x4485, [0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27], ); -/// As Grand Theft Auto VI (2026) asks for it; it calls 0x28 (take a +/// As the title (2026) asks for it; it calls 0x28 (take a /// screenshot) with the public API's arguments. pub const CAPTURE_IID_2026: Guid = Guid::new( 0x22e6_72d7, @@ -104,7 +104,7 @@ extern "system" fn acquire_deferral(_: This, out: *mut *mut c_void) -> HRESULT { unsafe { windows_sys::Win32::Foundation::CloseHandle(request) }; return hr; } - super::xgameruntime::put(out, request) + put(out, request) } #[cfg(windows)] diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index a932b7e..4c17b8e 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -1,7 +1,7 @@ //! The console's DirectStorage (`XCRDAPI.dll`): a factory that opens files //! and creates request queues and status arrays the title polls. Its //! interfaces have grown since 2020 (new interface ids, new slots); the -//! slots here are the ones Grand Theft Auto VI calls, read from its call +//! slots here are the ones the title calls, read from its call //! sites. Slots nobody has needed yet log their offset. //! //! Submitted requests of every queue run on one pool of workers, as the @@ -31,7 +31,7 @@ use super::xasync::{E_INVALIDARG, E_NOTIMPL, E_PENDING}; use super::xgameruntime::{Guid, HRESULT, Methods, Object, S_OK, add_ref, missing, put}; use crate::{HleModule, hle_export}; -/// The factory interface Grand Theft Auto VI asks for. +/// The factory interface the title asks for. const FACTORY: Guid = Guid::new( 0x6295_9d11, 0xd45f, @@ -141,10 +141,12 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out tracing::warn!(path = name, %error, "dstorage: opening a file failed"); return from_win32(&error); } + let kept = name.clone(); 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 }); + WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept)); put(out, file) } @@ -171,7 +173,7 @@ extern "system" fn create_status_array( } /// The queue's description: as in 2020 (source type, capacity, priority, -/// name), plus a field Grand Theft Auto VI sets to 1. +/// name), plus a field the title sets to 1. #[repr(C)] struct QueueDesc { source_type: u64, @@ -216,7 +218,7 @@ extern "system" fn create_queue( ) } -/// Grand Theft Auto VI asks for 32 MiB and stops if this fails. +/// The title asks for 32 MiB and stops if this fails. extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT { tracing::info!(size, "dstorage: staging buffer size"); if let Some(scheduler) = scheduler() { @@ -289,7 +291,7 @@ extern "system" fn status_result(this: Array, index: u32) -> HRESULT { .map_or(E_INVALIDARG, |e| e.load(Ordering::Acquire)) } -/// Grand Theft Auto VI polls this (entry 0, a `Sleep(1)` loop) and never +/// The title polls this (entry 0, a `Sleep(1)` loop) and never /// reads the result itself. extern "system" fn is_complete(this: Array, index: u32) -> bool { status_result(this, index) != E_PENDING @@ -440,20 +442,64 @@ impl Scheduler { } } +/// The walls trace (`VICTORY_WALLS_TRACE`): 0 or unset: off; 1: a line for +/// every read request that fails, with its file; 2: for every request (the +/// list of a launch's reads, by file and offset, is what a launch with the +/// first room's walls and one without are compared by). +fn walls_trace() -> u8 { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + std::env::var("VICTORY_WALLS_TRACE").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) + }) +} + +/// The files opened, by the address of our file object, with their paths +/// (for the walls trace: a request names its file by that address). +static WALLS_FILES: Mutex> = Mutex::new(Vec::new()); + +/// The walls trace's line for a request that is done. +fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std::time::Instant) { + let level = walls_trace(); + if level == 0 || (level == 1 && result.is_ok()) { + return; + } + let file = if request.options & MEMORY_SOURCE != 0 { + "memory".to_string() + } else { + let files = WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()); + let source = request.source as usize; + files.iter().find(|f| f.0 == source).map_or_else(|| "?".to_string(), |f| f.1.clone()) + }; + let hr = match result { + Ok(()) => 0, + Err(hr) => *hr as u32, + }; + tracing::info!( + file, + offset = request.offset, + source_size = request.source_size, + destination_size = request.destination_size, + to_pages = request.options & PAGE_DESTINATION != 0, + options = format_args!("{:#x}", request.options), + ms = started.elapsed().as_millis() as u64, + ok = result.is_ok(), + hr = format_args!("{hr:#010x}"), + "walls trace: a read request is done" + ); +} + /// A worker: runs the next read of the most deserving queue. fn work(scheduler: &'static Scheduler) { let mut lanes = scheduler.lock(); loop { let Some(job) = lanes.start() else { - lanes = scheduler - .work - .wait(lanes) - .unwrap_or_else(|e| e.into_inner()); + lanes = scheduler.work.wait(lanes).unwrap_or_else(|e| e.into_inner()); continue; }; drop(lanes); let started = std::time::Instant::now(); let result = execute(&job.request); + walls_request(&job.request, &result, started); lanes = scheduler.lock(); lanes.finish(&job, result); lanes.count(&job, started); @@ -487,8 +533,7 @@ impl Lanes { reading_workers = format_args!("{:.2}", reading / elapsed.as_secs_f64()), staging_waits = std::mem::take(&mut self.refused), bcpack_mb = self.bcpack.0 / 1_000_000, - bcpack_workers = - format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()), + bcpack_workers = format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()), waiting, "dstorage: last {:.1} s", elapsed.as_secs_f64() @@ -600,11 +645,7 @@ impl Lane { fn flush(&mut self) { while let Some(&(seq, _)) = self.statuses.front() { let waiting = self.reads.front().map(|r| r.0); - if waiting - .into_iter() - .chain(self.running.first().copied()) - .any(|s| s < seq) - { + if waiting.into_iter().chain(self.running.first().copied()).any(|s| s < seq) { return; } let Some((_, status)) = self.statuses.pop_front() else { @@ -675,7 +716,7 @@ struct Request { source_size: u32, /// Compressed size between two decompression stages; unused here. intermediate_size: u32, - /// Matched by cancellation; Grand Theft Auto VI leaves it 0. + /// Matched by cancellation; the title leaves it 0. tag: u64, name: *const c_char, } @@ -688,7 +729,7 @@ const BCPACK: u64 = 0xf << 1; const PAGE_DESTINATION: u64 = 1 << 21; const MEMORY_SOURCE: u64 = 1 << 22; // Bits 5-20 select a further transform, bit 23 a source in physical pages; -// Grand Theft Auto VI's packages need neither, so requests with them fail. +// The title's packages need neither, so requests with them fail. const PAGE: usize = 64 * 1024; @@ -697,6 +738,7 @@ enum Command { Status(Status), } + /// A status entry to write, holding a reference on its array. struct Status { array: Array, @@ -785,7 +827,7 @@ extern "system" fn submit(this: QueueRef) { /// Ends the queue whatever its reference count: what was not started never /// completes, and this returns once the reads already running have -/// finished. Grand Theft Auto VI calls this, not `Release`. +/// finished. The title calls this, not `Release`. extern "system" fn close(this: QueueRef) { // SAFETY: as above. close_lane(unsafe { &*this }.state.id); @@ -824,18 +866,14 @@ fn execute(request: &Request) -> Result<(), HRESULT> { return into_destination(request, size, |out| read_into(request, out).map(|()| size)) .map_err(|hr| fail(hr, "copying")); } - let tables = if bc != 0 { - Some(bcpack_tables()?) - } else { - None - }; + let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; // The console's order: zlib first, then BCPack. let source = if bc != 0 && options & ZLIB != 0 { - Cow::Owned( - inflate_intermediate(&source, request.intermediate_size as usize) - .map_err(|hr| fail(hr, "zlib"))?, - ) + let mut packed = vec![0; request.intermediate_size as usize]; + let n = inflate(&source, &mut packed).map_err(|hr| fail(hr, "zlib"))?; + packed.truncate(n); + Cow::Owned(packed) } else { source }; @@ -858,20 +896,47 @@ fn execute(request: &Request) -> Result<(), HRESULT> { /// that ends short of `out` passes: the title's chunks fill it exactly, and /// nothing says that is required. fn inflate(source: &[u8], out: &mut [u8]) -> Result { - miniz_oxide::inflate::decompress_slice_iter_to_slice(out, std::iter::once(source), true, false) - .map_err(inflate_error) -} - -/// The BCPack intermediate may be shorter than its limit. Grow its -/// storage as bytes arrive instead of reserving the entire limit up front. -fn inflate_intermediate(source: &[u8], limit: usize) -> Result, HRESULT> { - miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(source, limit) - .map_err(|error| inflate_error(error.status)) -} - -fn inflate_error(status: miniz_oxide::inflate::TINFLStatus) -> HRESULT { - tracing::debug!(?status, "dstorage: zlib stream"); - INVALID_DATA + thread_local! { + static INFLATE: std::cell::RefCell = + std::cell::RefCell::new(zlib_rs::Inflate::new(true, 15)); + } + INFLATE.with_borrow_mut(|state| { + state.reset(true); + // `Inflate::decompress` cannot distinguish a valid empty stream from + // an insufficient buffer when `avail_out == 0`, so use a 1-byte scratch + // destination and verify `written <= out_len` afterward. + let out_len = out.len(); + let mut scratch = [0u8; 1]; + let dest = if out_len == 0 { &mut scratch[..] } else { out }; + let (mut in_pos, mut out_pos) = (0usize, 0usize); + let status = loop { + match state.decompress( + &source[in_pos..], + &mut dest[out_pos..], + zlib_rs::InflateFlush::NoFlush, + ) { + Ok(zlib_rs::Status::StreamEnd) => break Ok(zlib_rs::Status::StreamEnd), + Ok(zlib_rs::Status::Ok) => { + let next_in = state.total_in() as usize; + let next_out = state.total_out() as usize; + if next_in == in_pos && next_out == out_pos { + break Ok(zlib_rs::Status::BufError); + } + in_pos = next_in; + out_pos = next_out; + } + other => break other, + } + }; + let written = state.total_out() as usize; + match status { + Ok(zlib_rs::Status::StreamEnd) if written <= out_len => Ok(written), + other => { + tracing::debug!(?other, "dstorage: zlib stream"); + Err(INVALID_DATA) + } + } + }) } /// The BCPack format's constant tables, parsed once for the process. If @@ -909,9 +974,7 @@ fn use_bcpack_tables(dir: std::path::PathBuf) { #[cfg(test)] fn load_bcpack_tables() -> Result { - let dir = BCPACK_DIR - .get() - .ok_or("no folder set for the test tables")?; + let dir = BCPACK_DIR.get().ok_or("no folder set for the test tables")?; let bytes = std::fs::read(dir.join("tables.bin")).map_err(|e| e.to_string())?; Tables::parse(&bytes).map_err(|e| e.to_string()) } @@ -937,9 +1000,7 @@ static READING: AtomicU64 = AtomicU64::new(0); fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { if request.options & MEMORY_SOURCE != 0 { // SAFETY: the title's source holds `out.len()` bytes until completion. - out.copy_from_slice(unsafe { - std::slice::from_raw_parts(request.source.cast(), out.len()) - }); + out.copy_from_slice(unsafe { std::slice::from_raw_parts(request.source.cast(), out.len()) }); return Ok(()); } // SAFETY: a file object we created; the title keeps it open. @@ -997,15 +1058,45 @@ fn into_destination( } let mut data = vec![0; len]; let n = fill(&mut data)?; - if super::xmem::write_physical(pages, offset, &data[..n]) { + // A page the title has just made, or a view the host refuses for a moment (commit + // or address space short while a load maps many at once), can come right a little + // later: tried again before the request fails (`VICTORY_DSTORAGE_RETRIES`, default 12, + // about 1.5 s in all). + static RETRIES: std::sync::OnceLock = std::sync::OnceLock::new(); + let retries = *RETRIES.get_or_init(|| { + std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.parse().ok()).unwrap_or(12) + }); + let mut written = super::xmem::write_physical(pages, offset, &data[..n]); + let mut tries = 0; + while !written && tries < retries { + std::thread::sleep(std::time::Duration::from_millis((2u64 << tries.min(6)).min(128))); + tries += 1; + written = super::xmem::write_physical(pages, offset, &data[..n]); + } + if written { + if tries > 0 { + tracing::info!(offset, len, tries, "dstorage: a destination's physical pages written after a retry"); + } Ok(()) } else { + let known = super::xmem::pages_known(pages, offset, len); + tracing::warn!(known, last_error = std::io::Error::last_os_error().raw_os_error(), "dstorage: retries used up"); + // Said aloud: the title never reads a request's result + // (it only polls for completion), so a destination left unwritten + // is a model or texture that silently holds whatever its pages + // held before. + tracing::warn!( + offset, + len, + pages = pages.len(), + "dstorage: a destination's physical pages could not be written (unknown page or a host failure); its request fails" + ); Err(E_INVALIDARG) } } -/// Slots by the 2020 order, which the argument shapes at Grand Theft Auto -/// VI's call sites match (0x18, 0x20, 0x30 and 0x40 are called). +/// Slots by the 2020 order, which the argument shapes at +/// the title's call sites match (0x18, 0x20, 0x30 and 0x40 are called). static QUEUE_VTABLE: Methods<12> = Methods([ missing::<0> as *const (), add_ref_instance:: as *const (), @@ -1167,10 +1258,18 @@ mod tests { assert_eq!(std::mem::offset_of!(QueueDesc, unknown), 0x18); } + fn compress_zlib(plain: &[u8]) -> Vec { + let mut buf = vec![0u8; zlib_rs::compress_bound(plain.len())]; + let (packed, rc) = + zlib_rs::compress_slice(&mut buf, plain, zlib_rs::DeflateConfig::new(6)); + assert_eq!(rc, zlib_rs::ReturnCode::Ok); + packed.to_vec() + } + #[test] fn raw_and_zlib_reads_from_a_file() { let plain = pattern(300_000); - let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let packed = compress_zlib(&plain); let mut contents = plain.clone(); contents.extend_from_slice(&packed); let (_dir, file) = file_with(&contents); @@ -1202,7 +1301,7 @@ mod tests { #[test] fn memory_sources_inflate_too() { let plain = pattern(70_000); - let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let packed = compress_zlib(&plain); let (queue, array) = (new_queue(1), status_array(1)); let mut out = vec![0u8; plain.len()]; let options = ZLIB | MEMORY_SOURCE; @@ -1229,8 +1328,7 @@ mod tests { // Requests in flight together run in any order, so none of them // shares a destination (failed ones leave theirs undefined). let mut buffers = [[0u8; 16]; 5]; - let [failed, failed_too, out, other, bcpack] = - buffers.each_mut().map(|b| b.as_mut_ptr().cast()); + let [failed, failed_too, out, other, bcpack] = buffers.each_mut().map(|b| b.as_mut_ptr().cast()); // Segment 0: a read past the end, then a bad stream; the first wins. enqueue(queue, &request(0, failed, 16, file, 4090, 16)); @@ -1377,29 +1475,10 @@ mod tests { assert_eq!(results(), (INVALID_DATA, S_OK)); } - #[test] - fn zlib_intermediate_grows_with_output_and_respects_its_limit() { - let data = [0x69; 2048]; - let mut encoded = miniz_oxide::deflate::compress_to_vec_zlib(&data, 6); - let limit = 64 << 20; - let decoded = inflate_intermediate(&encoded, limit).unwrap(); - assert_eq!(decoded, data); - assert!(decoded.capacity() < limit); - assert_eq!(inflate_intermediate(&encoded, data.len()).unwrap(), data); - assert_eq!( - inflate_intermediate(&encoded, data.len() - 1), - Err(INVALID_DATA) - ); - - // The checksum is still checked, even with room left over. - *encoded.last_mut().unwrap() ^= 1; - assert_eq!(inflate_intermediate(&encoded, limit), Err(INVALID_DATA)); - } - #[test] fn zlib_then_bcpack() { with_test_tables(); - let packed = miniz_oxide::deflate::compress_to_vec_zlib(&BC4_STREAM, 6); + let packed = compress_zlib(&BC4_STREAM); let (_dir, file) = file_with(&packed); let (queue, array) = (new_queue(0), status_array(1)); let mut out = [0u8; 16]; @@ -1465,10 +1544,7 @@ mod tests { let (_dir, file) = file_with(&contents); let (queue, array) = (new_queue(0), status_array(1)); let mut out = [0u8; 16]; - enqueue( - queue, - &request(4 << 1, out.as_mut_ptr().cast(), 16, file, 100, 88), - ); + enqueue(queue, &request(4 << 1, out.as_mut_ptr().cast(), 16, file, 100, 88)); enqueue_status(queue, array, 0); void(queue, 0x30); assert_eq!(wait(array, 0), S_OK); @@ -1544,7 +1620,7 @@ mod tests { }; let (a, b) = (allocate(3), allocate(1)); let plain = pattern(2 * PAGE + 100); - let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let packed = compress_zlib(&plain); // One allocation's pages in order (one window), then pages of two // (through a buffer), both from 50 bytes into the first. let mut destinations = [a.clone(), vec![a[0], a[1], b[0]]]; @@ -1589,4 +1665,61 @@ mod tests { assert_eq!(xmem::XMemFreePhysicalPages(3, a.as_ptr()), 1); assert_eq!(xmem::XMemFreePhysicalPages(1, b.as_ptr()), 1); } + + #[test] + fn zlib_inflate_handles_short_exact_empty_and_bad_streams() { + let plain = pattern(65_537); + let packed = compress_zlib(&plain); + + // Exact fit. + let mut exact = vec![0u8; plain.len()]; + assert_eq!(inflate(&packed, &mut exact), Ok(plain.len())); + assert_eq!(exact, plain); + + // Short stream into a larger buffer passes and returns bytes written; + // guard bytes outside the slice passed to `inflate` stay untouched. + let mut larger = vec![0xAA; plain.len() + 64]; + assert_eq!( + inflate(&packed, &mut larger[..plain.len() + 32]), + Ok(plain.len()) + ); + assert_eq!(&larger[..plain.len()], &plain[..]); + assert!(larger[plain.len() + 32..].iter().all(|&b| b == 0xAA)); + + // Empty valid stream passes for empty or non-empty destinations. + let empty = compress_zlib(&[]); + assert_eq!(inflate(&empty, &mut []), Ok(0)); + let mut scratch = [0x55u8; 4]; + assert_eq!(inflate(&empty, &mut scratch), Ok(0)); + + // Oversized stream (destination too small, including empty) fails. + let mut small = vec![0u8; plain.len() - 1]; + assert_eq!(inflate(&packed, &mut small), Err(INVALID_DATA)); + assert_eq!(inflate(&packed, &mut []), Err(INVALID_DATA)); + + // Truncated stream (missing trailer or payload bytes) fails. + let mut out = vec![0u8; plain.len()]; + assert_eq!( + inflate(&packed[..packed.len() - 1], &mut out), + Err(INVALID_DATA) + ); + assert_eq!( + inflate(&packed[..packed.len() / 2], &mut out), + Err(INVALID_DATA) + ); + assert_eq!(inflate(&[], &mut out), Err(INVALID_DATA)); + + // Corrupt Adler-32 trailer fails. + let mut bad_adler = packed.clone(); + *bad_adler.last_mut().unwrap() ^= 1; + assert_eq!(inflate(&bad_adler, &mut out), Err(INVALID_DATA)); + + // Corrupt header/payload fails, and subsequent valid inflate on the + // same thread still succeeds (verifies thread-local state reset). + let mut bad_body = packed.clone(); + bad_body[2] ^= 0xFF; + assert_eq!(inflate(&bad_body, &mut out), Err(INVALID_DATA)); + assert_eq!(inflate(&packed, &mut out), Ok(plain.len())); + assert_eq!(out, plain); + } } diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index 83087f9..902c4a9 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -516,7 +516,7 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi // Kernel reads into title memory. The GPU side leaves blocks of title GPU // buffers read-only to see the title's next write, and the kernel's writes -// fail there instead of faulting into its handler; Grand Theft Auto VI's +// fail there instead of faulting into its handler; the title's // synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned // destinations and retry a failed `ReadFile` forever. So the destination // is opened first. @@ -747,10 +747,7 @@ mod tests { let file = std::fs::File::open(&path).unwrap(); let (mut out, mut n) = ([0u8; 10], 0); let handle = file.as_raw_handle().cast(); - assert_ne!( - ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), - 0 - ); + assert_ne!(ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), 0); assert_eq!((&out, n), (b"0123456789", 10)); } diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 266cb22..6cb89fa 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1,6 +1,6 @@ //! `gameinput.dll`: input devices from the host. Gamepads come from XInput -//! (host slots 0-3); while none is active, the keyboard drives one stand-in -//! gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own +//! (host slots 0-3); while none is connected, the keyboard drives one +//! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own //! too. A poll thread turns host state into readings (a new one per change) //! and runs device callbacks on connect and disconnect. #![allow(non_snake_case)] @@ -93,24 +93,6 @@ struct PadState { right_y: f32, } -/// XInput rest thresholds (`XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE` and -/// `XINPUT_GAMEPAD_TRIGGER_THRESHOLD`), so virtual or untouched controllers -/// do not silence the keyboard stand-in pad. -const STICK_DEADZONE: f32 = 8689.0 / 32767.0; -const TRIGGER_DEADZONE: f32 = 30.0 / 255.0; - -impl PadState { - fn is_active(&self) -> bool { - self.buttons != 0 - || self.left_trigger > TRIGGER_DEADZONE - || self.right_trigger > TRIGGER_DEADZONE - || self.left_x.abs() > STICK_DEADZONE - || self.left_y.abs() > STICK_DEADZONE - || self.right_x.abs() > STICK_DEADZONE - || self.right_y.abs() > STICK_DEADZONE - } -} - /// One key held down: scan code (0xE0xx when extended), character, key. #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] @@ -338,9 +320,6 @@ struct Slot { struct State { slots: [Slot; DEVICES], - /// Host pad slots that have reported input outside rest thresholds since - /// connecting (cleared when all host pads are idle and fallback keys fire). - engaged: [bool; PADS], callbacks: Vec, /// Asynchronous enumerations, delivered by the next poll. pending: Vec, @@ -387,7 +366,6 @@ impl Hub { source: Mutex::new(source), state: Mutex::new(State { slots: Default::default(), - engaged: [false; PADS], callbacks: Vec::new(), pending: Vec::new(), running: Vec::new(), @@ -476,26 +454,11 @@ impl State { ) -> Vec { let now = now(); let mut events = std::mem::take(&mut self.pending); - let mut any_active = false; - for (slot, pad) in pads.iter().enumerate() { - match pad { - Some(p) if p.is_active() => { - self.engaged[slot] = true; - any_active = true; - } - None => self.engaged[slot] = false, - _ => {} - } - } - let stand_in = fallback(&keys); - if !any_active && stand_in != PadState::default() { - self.engaged = [false; PADS]; - } - let using_pad = self.engaged.iter().any(|&e| e); + let any_pad = pads.iter().any(Option::is_some); for (slot, pad) in pads.into_iter().enumerate() { self.update(devices, slot, pad.map(Value::Pad), now, &mut events); } - let fallback = (!using_pad).then_some(Value::Pad(stand_in)); + let fallback = (!any_pad).then(|| Value::Pad(fallback(&keys))); self.update(devices, FALLBACK, fallback, now, &mut events); self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events); events @@ -639,7 +602,7 @@ extern "system" fn current_reading( }; let found = if device.is_null() { (0..DEVICES) - .filter(|&i| state.slots[i].connected && (i >= PADS || state.engaged[i])) + .filter(|&i| state.slots[i].connected) .filter_map(newest) .max_by_key(|r| r.timestamp) } else { @@ -674,7 +637,7 @@ fn relative( // SAFETY: a reading we handed out and the title still holds. let reference = unsafe { &*reference }; // shortcut: with no device given only the reference's device is walked, - // not every device's readings in time order; Grand Theft Auto VI walks + // not every device's readings in time order; the title walks // only keyboard readings (one device) and the current pad's previous one. let Some(index) = hub.index(reference.device) else { return fail(out, E_INVALIDARG); @@ -749,7 +712,7 @@ fn token(out: *mut u64) -> HRESULT { S_OK } -// shortcut: reading callbacks never run; Grand Theft Auto VI registers none +// shortcut: reading callbacks never run; the title registers none // (it polls). extern "system" fn register_reading( _: This, @@ -855,10 +818,7 @@ extern "system" fn unregister_callback(this: This, token: u64, timeout: u64) -> return true; } state = match deadline { - None => hub - .returned - .wait(state) - .unwrap_or_else(PoisonError::into_inner), + None => hub.returned.wait(state).unwrap_or_else(PoisonError::into_inner), Some(deadline) => { let Some(left) = deadline.checked_duration_since(Instant::now()) else { return false; @@ -951,7 +911,7 @@ extern "system" fn device_status(this: *const Device) -> u32 { // shortcut: trigger motors are dropped (XInput has none). The host API that // drives them without a redistributable is Windows.Gaming.Input (WinRT // `Gamepad.Vibration`), which needs WinRT bindings this crate lacks outside -// diagnostics builds; Grand Theft Auto VI sends trigger levels in slot 0x50. +// diagnostics builds; the title sends trigger levels in slot 0x50. extern "system" fn set_rumble(this: *const Device, params: *const [f32; 4]) { // SAFETY: one of our devices. let device = unsafe { &*this }; @@ -1184,7 +1144,21 @@ mod host { return None; } self.empty_until[slot] = None; - Some(convert(&state.Gamepad)) + #[allow(unused_mut)] + let mut pad = convert(&state.Gamepad); + // The scripted keys (`VICTORY_KEYS`) also press the first + // pad's buttons, by the stand-in pad's table: with a real pad + // connected the stand-in is not there, and a title that listens + // to the pad (the title's start screen) saw nothing. + #[cfg(feature = "diagnostics")] + if slot == 0 { + for vk in scripted() { + if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) { + pad.buttons |= button; + } + } + } + Some(pad) } fn keys(&mut self) -> Vec { @@ -1207,8 +1181,8 @@ mod host { // SAFETY: plain query. scan_code: unsafe { MapVirtualKeyW(u32::from(vk), MAPVK_VK_TO_VSC_EX) }, virtual_key: vk, - // shortcut: no characters (code point 0); Grand Theft - // Auto VI reads scan codes and virtual keys only. + // shortcut: no characters (code point 0); + // the title reads scan codes and virtual keys only. ..Default::default() }) .collect() @@ -1604,16 +1578,7 @@ mod tests { let mut token = 0; let context = (&raw const hub.object).cast_mut().cast(); assert_eq!( - register( - &hub.object, - std::ptr::null(), - GAMEPAD_KIND, - 1, - 0, - context, - Some(slow), - &mut token - ), + register(&hub.object, std::ptr::null(), GAMEPAD_KIND, 1, 0, context, Some(slow), &mut token), S_OK ); host.lock().unwrap().pads[1] = Some(PadState::default()); @@ -1622,10 +1587,7 @@ mod tests { std::thread::sleep(Duration::from_millis(1)); } let unregister = slot:: bool, _>(&hub.object, 0x68); - assert!( - !unregister(&hub.object, token, 5000), - "times out while it runs" - ); + assert!(!unregister(&hub.object, token, 5000), "times out while it runs"); let leave = std::thread::spawn(|| { std::thread::sleep(Duration::from_millis(50)); LEAVE.store(true, Ordering::SeqCst); @@ -1664,109 +1626,4 @@ mod tests { rumble(device, std::ptr::null()); assert_eq!(host.lock().unwrap().rumble, [(2, 32767, 65535), (2, 0, 0)]); } - - fn current_any(hub: &Hub, kind: u32) -> Result<*const Reading, HRESULT> { - type Current = extern "system" fn(This, u32, *const Device, Out) -> HRESULT; - let mut out = std::ptr::null(); - let hr = - slot::(&hub.object, 0x20)(&hub.object, kind, std::ptr::null(), &mut out); - result(hr, out) - } - - #[test] - fn idle_host_pads_keep_the_keyboard_stand_in_until_active() { - let (hub, host) = fake(); - let log = Log::default(); - register(hub, GAMEPAD_KIND, 2, &log); - assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); - - // 1. An all-zero virtual XInput pad (e.g. a keyboard presenting an unused - // XInput slot) connects its own slot without disconnecting `FALLBACK`. - host.lock().unwrap().pads[0] = Some(PadState::default()); - hub.poll(); - assert_eq!(log.lock().unwrap()[1..], [(0, STATUS_CONNECTED, 0)]); - - host.lock().unwrap().keys = vec![key(0x0D), key(b'W')]; - hub.poll(); - let stand_in = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); - assert_eq!( - pad(stand_in), - PadState { - buttons: A, - left_y: 1.0, - ..Default::default() - } - ); - release(stand_in); - - // Sub-deadzone stick/trigger drift on slot 0 does not steal null-device - // `GetCurrentReading(GAMEPAD_KIND, null)` away from `FALLBACK`. - std::thread::sleep(Duration::from_millis(2)); - host.lock().unwrap().pads[0] = Some(PadState { - left_x: 0.15, - right_y: -0.20, - left_trigger: 0.05, - ..Default::default() - }); - hub.poll(); - let any = current_any(hub, GAMEPAD_KIND).unwrap(); - assert_eq!(pad(any).buttons, A); - release(any); - - // Releasing keys keeps `FALLBACK` connected and reports the neutral edge. - host.lock().unwrap().keys.clear(); - hub.poll(); - let rest = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); - assert_eq!(pad(rest), PadState::default()); - release(rest); - - // 2. Real input outside deadzone on slot 1 disconnects `FALLBACK` and - // takes priority even while slot 0 keeps sub-deadzone jitter. - let active_pad = PadState { - buttons: B, - left_x: 0.6, - ..Default::default() - }; - host.lock().unwrap().pads[1] = Some(active_pad); - hub.poll(); - assert_eq!( - log.lock().unwrap()[2..], - [(1, STATUS_CONNECTED, 0), (FALLBACK, 0, STATUS_CONNECTED)] - ); - assert_eq!( - current(hub, GAMEPAD_KIND, FALLBACK), - Err(DEVICE_DISCONNECTED) - ); - - std::thread::sleep(Duration::from_millis(2)); - host.lock().unwrap().pads[0] = Some(PadState { - left_x: 0.12, - ..Default::default() - }); - hub.poll(); - let any = current_any(hub, GAMEPAD_KIND).unwrap(); - assert_eq!(pad(any), active_pad); - release(any); - - // Releasing the physical controller back to neutral keeps pad mode engaged - // without reconnecting `FALLBACK` between button presses. - host.lock().unwrap().pads[1] = Some(PadState::default()); - hub.poll(); - assert_eq!( - current(hub, GAMEPAD_KIND, FALLBACK), - Err(DEVICE_DISCONNECTED) - ); - let neutral_pad = current_any(hub, GAMEPAD_KIND).unwrap(); - assert_eq!(pad(neutral_pad), PadState::default()); - release(neutral_pad); - - // 3. Pressing a fallback key while all host pads are idle hands control - // back to `FALLBACK` cleanly. - host.lock().unwrap().keys = vec![key(0x0D)]; - hub.poll(); - assert_eq!(log.lock().unwrap()[4..], [(FALLBACK, STATUS_CONNECTED, 0)]); - let back = current_any(hub, GAMEPAD_KIND).unwrap(); - assert_eq!(pad(back).buttons, A); - release(back); - } } diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index affdd7f..3ab3067 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -597,7 +597,6 @@ mod tests { use super::*; #[test] - #[cfg_attr(not(windows), ignore = "title paths are Windows paths")] fn title_images_report_their_original_path() { let base = 0x7000_0000_0000; runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe")); @@ -656,7 +655,6 @@ mod tests { } #[test] - #[cfg_attr(not(windows), ignore = "title paths are Windows paths")] fn title_dlls_and_pseudo_modules_are_found_by_name() { let base = 0x7100_0000_0000usize; runtime::set_image_path(base, std::path::Path::new(r"C:\title\Mapped.dll")); diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index 4eb9649..f1b5777 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -110,8 +110,8 @@ pub extern "system" fn CreateWindowExA( hwnd } -/// A console title sizes its window to its render target (Grand Theft -/// Auto VI: 3840x2160 on a Series X), which can exceed the host's screen. +/// A console title sizes its window to its render target ( +/// the title: 3840x2160 on a Series X), which can exceed the host's screen. /// A top-level window larger than the work area is shrunk to fit, keeping /// its proportions, and centred; what it shows is scaled to it (the swap /// chain stretches). @@ -177,8 +177,8 @@ extern "system" fn window_proc( // Alt or F10 puts a window into menu mode: the system runs a modal menu // loop on the thread that owns the window, which is the title's. The // title then stops (no frames, no input) until a key ends the loop, and - // nothing shows it, since the window has no menu bar; Grand Theft Auto - // VI aborts itself about half a minute later. A console has no window + // nothing shows it, since the window has no menu bar; + // the title aborts itself about half a minute later. A console has no window // menu. The mouse still opens it from the title bar. if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_KEYMENU as usize { return 0; diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs index 16d593a..51e3590 100644 --- a/crates/victory-hle/src/modules/mod.rs +++ b/crates/victory-hle/src/modules/mod.rs @@ -45,7 +45,7 @@ pub mod xuser; use crate::HleModule; pub(crate) fn all() -> Vec { - vec![ + let mut all = vec![ kernel::module(), xgameruntime::module(), gameinput::module(), @@ -53,21 +53,22 @@ pub(crate) fn all() -> Vec { audio::module(), dsp::module(), xg::module(), - #[cfg(windows)] - apu::module(), - #[cfg(windows)] - media::module(), - #[cfg(windows)] - dstorage::module(), - #[cfg(windows)] - files::module(), - #[cfg(windows)] - lifecycle::module(), - #[cfg(windows)] - net::module(), - #[cfg(windows)] - xmem::module(), - #[cfg(windows)] - xsystem::module(), - ] + ]; + #[cfg(windows)] + all.push(apu::module()); + #[cfg(windows)] + all.push(media::module()); + #[cfg(windows)] + all.push(dstorage::module()); + #[cfg(windows)] + all.push(files::module()); + #[cfg(windows)] + all.push(lifecycle::module()); + #[cfg(windows)] + all.push(net::module()); + #[cfg(windows)] + all.push(xmem::module()); + #[cfg(windows)] + all.push(xsystem::module()); + all } diff --git a/crates/victory-hle/src/modules/net.rs b/crates/victory-hle/src/modules/net.rs index 76595d1..857b351 100644 --- a/crates/victory-hle/src/modules/net.rs +++ b/crates/victory-hle/src/modules/net.rs @@ -307,77 +307,22 @@ pub extern "system" fn WSAConnectByList( timeout: *const c_void, reserved: *mut c_void, ) -> i32 { - // SAFETY: the title passes a `SOCKET_ADDRESS_LIST` or null. - let entries = (!list.is_null()).then(|| unsafe { - let count = usize::try_from(list.cast::().read()).unwrap_or(0); - std::slice::from_raw_parts(list.add(8).cast::(), count) - }); - if let Some(entries) = entries - && !entries + if !list.is_null() { + // SAFETY: the title passes a `SOCKET_ADDRESS_LIST`. + let entries = unsafe { + let count = usize::try_from(list.cast::().read()).unwrap_or(0); + std::slice::from_raw_parts(list.add(8).cast::(), count) + }; + if !entries .iter() .all(|e| reachable("network connect blocked", e.addr, e.len)) - { - return 0; - } - static HOST: std::sync::OnceLock> = std::sync::OnceLock::new(); - match *HOST.get_or_init(|| crate::host::function("ws2_32.dll", "WSAConnectByList")) { - Some(address) => { - type ConnectByList = extern "system" fn( - Socket, - *const u8, - *mut u32, - *mut c_void, - *mut u32, - *mut c_void, - *const c_void, - *mut c_void, - ) -> i32; - // SAFETY: the host's export, with this signature. - let host = unsafe { std::mem::transmute::(address) }; - host( - s, list, local_len, local, remote_len, remote, timeout, reserved, - ) + { + return 0; } - None => connect_each( - s, - entries.unwrap_or_default(), - local_len, - local, - remote_len, - remote, - ), - } -} - -/// `WSAConnectByList` where the host lacks it (Wine): `connect` to each -/// candidate in turn until one takes. Blocking; the timeout is not kept. -fn connect_each( - s: Socket, - entries: &[SocketAddress], - local_len: *mut u32, - local: *mut c_void, - remote_len: *mut u32, - remote: *mut c_void, -) -> i32 { - const WSAEINVAL: i32 = 10022; - type Name = extern "system" fn(Socket, *mut c_void, *mut i32) -> i32; - let connect = host!("ws2_32.dll", "connect": extern "system" fn(Socket, *const u8, i32) -> i32); - let set_error = host!("ws2_32.dll", "WSASetLastError": extern "system" fn(i32)); - if entries.is_empty() { - set_error(WSAEINVAL); - return 0; } - if !entries.iter().any(|e| connect(s, e.addr, e.len) == 0) { - // `connect` left the last candidate's error. - return 0; - } - if !local.is_null() && !local_len.is_null() { - host!("ws2_32.dll", "getsockname": Name)(s, local, local_len.cast()); - } - if !remote.is_null() && !remote_len.is_null() { - host!("ws2_32.dll", "getpeername": Name)(s, remote, remote_len.cast()); - } - 1 + host!("ws2_32.dll", "WSAConnectByList": extern "system" fn(Socket, *const u8, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)( + s, list, local_len, local, remote_len, remote, timeout, reserved, + ) } pub extern "system" fn WSAJoinLeaf( @@ -635,28 +580,7 @@ pub extern "system" fn GetAddrInfoExA( if !resolvable(narrow(name)) { return WSAHOST_NOT_FOUND; } - type GetAddrInfoExA = extern "system" fn( - *const c_char, - *const c_char, - u32, - *const c_void, - *const c_void, - *mut *mut c_void, - *const c_void, - *mut c_void, - *const c_void, - *mut Handle, - ) -> i32; - static HOST: std::sync::OnceLock> = std::sync::OnceLock::new(); - // Hosts without the ANSI form (Wine): the name does not resolve, as for - // one we block. - let Some(address) = *HOST.get_or_init(|| crate::host::function("ws2_32.dll", "GetAddrInfoExA")) - else { - return WSAHOST_NOT_FOUND; - }; - // SAFETY: the host's export, with this signature. - let host = unsafe { std::mem::transmute::(address) }; - host( + host!("ws2_32.dll", "GetAddrInfoExA": extern "system" fn(*const c_char, *const c_char, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)( name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle, ) } @@ -834,15 +758,14 @@ pub extern "system" fn WinHttpOpen( ) } -/// See [`WinHttpOpen`]: a proxy set later is accepted and not used. A handle -/// nobody opened is the host's to refuse. +/// See [`WinHttpOpen`]: a proxy set later is accepted and not used. pub extern "system" fn WinHttpSetOption( handle: Handle, option: u32, buffer: *const c_void, len: u32, ) -> i32 { - if option == WINHTTP_OPTION_PROXY && !handle.is_null() { + if option == WINHTTP_OPTION_PROXY { once("HTTP proxy ignored", "WINHTTP_OPTION_PROXY".into()); return 1; } @@ -960,1443 +883,187 @@ mod tests { use super::*; use victory_pe::ImportSymbol; - // Synthetic addresses only. TEST-NET-1 (192.0.2.0/24) and the IPv6 - // documentation prefix are never routed, and no test tries them. - const AWAY: [u8; 4] = [192, 0, 2, 1]; - const HOME: [u8; 4] = [127, 0, 0, 1]; - const AWAY6: [u8; 16] = [0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]; - const HOME6: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]; - fn v4(ip: [u8; 4], port: u16) -> [u8; 16] { - let mut addr = [0u8; 16]; - addr[..2].copy_from_slice(&AF_INET.to_le_bytes()); - addr[2..4].copy_from_slice(&port.to_be_bytes()); - addr[4..8].copy_from_slice(&ip); - addr - } - - fn v6(ip: [u8; 16], port: u16) -> [u8; 28] { - let mut addr = [0u8; 28]; - addr[..2].copy_from_slice(&AF_INET6.to_le_bytes()); - addr[2..4].copy_from_slice(&port.to_be_bytes()); - addr[8..24].copy_from_slice(&ip); - addr - } - - /// `text` as a title passes it to a `W` function. - fn utf16(text: &str) -> Vec { - text.encode_utf16().chain([0]).collect() - } - - /// Winsock starts on the first socket the process opens. - fn up() { - drop(std::net::TcpListener::bind("127.0.0.1:0").unwrap()); - } - - fn open(family: u16, kind: i32, protocol: i32) -> Socket { - host!("ws2_32.dll", "socket": extern "system" fn(i32, i32, i32) -> Socket)( - i32::from(family), - kind, - protocol, - ) - } - - fn close(socket: Socket) { - let _ = host!("ws2_32.dll", "closesocket": extern "system" fn(Socket) -> i32)(socket); - } - - fn last_error() -> i32 { - host!("ws2_32.dll", "WSAGetLastError": extern "system" fn() -> i32)() - } - - fn last_error_win32() -> u32 { - // SAFETY: no arguments. - unsafe { windows_sys::Win32::Foundation::GetLastError() } - } - - /// The address the kernel gave `socket`, and how many bytes of it. - fn bound_address(socket: Socket) -> ([u8; 128], i32) { - let mut addr = [0u8; 128]; - let mut len = addr.len() as i32; - assert_eq!( - host!("ws2_32.dll", "getsockname": extern "system" fn(Socket, *mut u8, *mut i32) -> i32)( - socket, - addr.as_mut_ptr(), - &mut len - ), - 0, - "getsockname: {}", - last_error() - ); - (addr, len) - } - - fn free_addrinfo(result: *mut c_void, wide: bool) { - if wide { - host!("ws2_32.dll", "FreeAddrInfoW": extern "system" fn(*mut c_void))(result); - } else { - host!("ws2_32.dll", "freeaddrinfo": extern "system" fn(*mut c_void))(result); - } - } - - /// A NUL-terminated narrow string the host wrote. - fn cstr(text: &[c_char]) -> String { - // SAFETY: the call that filled `text` terminated it. - unsafe { CStr::from_ptr(text.as_ptr()) } - .to_string_lossy() - .into_owned() - } - - /// A `SOCKET_ADDRESS_LIST`: an `i32` count, then `(pointer, length)` - /// pairs at 8 and 16 bytes. A `Vec` keeps it aligned for them. - fn address_list(entries: &[[u8; 16]]) -> Vec { - let mut list = vec![0u64; 1 + 2 * entries.len()]; - list[0] = u64::from(u32::try_from(entries.len()).unwrap()); - for (i, entry) in entries.iter().enumerate() { - list[1 + 2 * i] = entry.as_ptr() as usize as u64; - list[2 + 2 * i] = 16; - } - list + let mut a = [0u8; 16]; + a[..2].copy_from_slice(&AF_INET.to_le_bytes()); + a[2..4].copy_from_slice(&port.to_be_bytes()); + a[4..8].copy_from_slice(&ip); + a } - /// The first `WSAMSG` fields: where a datagram is going. - #[repr(C)] - struct WsaBuf { - len: u32, - buf: *mut u8, - } - - #[repr(C)] - struct WsaMsg { - name: *const u8, - namelen: i32, - buffers: *const WsaBuf, - count: u32, - control: WsaBuf, - flags: u32, - } - - /// `ADDRINFOW`, as the host lays it out. - #[repr(C)] - struct AddrInfo { - flags: i32, - family: i32, - kind: i32, - protocol: i32, - addr_len: usize, - canon_name: *mut u16, - addr: *const u8, - next: *mut AddrInfo, - } + // TEST-NET-1 (192.0.2.0/24): never routed, and never tried here. + const AWAY: [u8; 4] = [192, 0, 2, 1]; + const HOME: [u8; 4] = [127, 0, 0, 1]; #[test] - fn connect_by_list_falls_back_to_connect() { + fn only_loopback_is_reachable() { // Also starts Winsock for the raw calls below. let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); let socket = host!("ws2_32.dll", "socket": extern "system" fn(i32, i32, i32) -> Socket); let close = host!("ws2_32.dll", "closesocket": extern "system" fn(Socket) -> i32); + let last_error = host!("ws2_32.dll", "WSAGetLastError": extern "system" fn() -> i32); + let null = std::ptr::null_mut::(); + + // Connects. let s = socket(2, 1, 6); assert_ne!(s, INVALID_SOCKET); - let home = v4(HOME, port); - let entries = [SocketAddress { - addr: home.as_ptr(), - len: 16, - }]; - let (mut local, mut remote) = ([0u8; 16], [0u8; 16]); - let (mut local_len, mut remote_len) = (16u32, 16u32); - assert_eq!( - connect_each( - s, - &entries, - &mut local_len, - local.as_mut_ptr().cast(), - &mut remote_len, - remote.as_mut_ptr().cast(), - ), - 1 - ); - listener.accept().unwrap(); - assert_eq!(remote[2..8], home[2..8]); - assert_eq!(local[4..8], HOME); - close(s); + assert_eq!(connect(s, v4(AWAY, 80).as_ptr(), 16), SOCKET_ERROR); + assert_eq!(last_error(), WSAENETUNREACH); + let n = null.cast(); assert_eq!( - connect_each( + WSAConnectByNameA( s, - &[], - std::ptr::null_mut(), - std::ptr::null_mut(), - std::ptr::null_mut(), - std::ptr::null_mut(), + c"example.com".as_ptr(), + c"80".as_ptr(), + n, + null, + n, + null, + null, + null ), 0 ); - } - - #[test] - fn sockaddrs_are_read_by_family_and_length() { - assert_eq!( - socket_addr(v4(HOME, 8080).as_ptr(), 16), - Some(SocketAddr::from((HOME, 8080))) - ); - assert_eq!( - socket_addr(v6(HOME6, 443).as_ptr(), 28), - Some(SocketAddr::from((HOME6, 443))) - ); - assert_eq!( - socket_addr(v6(AWAY6, 0x1234).as_ptr(), 28), - Some(SocketAddr::from((AWAY6, 0x1234))) - ); - // The port is in network order. - let mut network = v4(HOME, 0); - network[2] = 0x12; - network[3] = 0x34; - assert_eq!(socket_addr(network.as_ptr(), 16).unwrap().port(), 0x1234); - - // Too short, not a family we know, or no buffer at all. - assert_eq!(socket_addr(std::ptr::null(), 16), None); - assert_eq!(socket_addr(network.as_ptr(), 0), None); - assert_eq!(socket_addr(network.as_ptr(), 3), None); - assert_eq!(socket_addr(network.as_ptr(), 15), None); - assert_eq!(socket_addr(network.as_ptr(), -1), None); - assert_eq!(socket_addr(v6(HOME6, 80).as_ptr(), 27), None); - let mut unknown = v4(HOME, 80); - unknown[..2].copy_from_slice(&99u16.to_le_bytes()); - assert_eq!(socket_addr(unknown.as_ptr(), 16), None); - // A `sockaddr_storage` is longer than what it holds. - let mut storage = [0u8; 128]; - storage[..16].copy_from_slice(&v4(HOME, 80)); - assert_eq!( - socket_addr(storage.as_ptr(), 128), - Some(SocketAddr::from((HOME, 80))) - ); - } - - #[test] - fn only_loopback_is_reachable() { - // Also starts Winsock for the raw calls below. - } - - #[test] - fn raw_addresses_are_read_by_family() { - assert_eq!( - raw_ip(HOME.as_ptr().cast(), 4, i32::from(AF_INET)), - Some(IpAddr::from(HOME)) - ); - assert_eq!( - raw_ip(HOME6.as_ptr().cast(), 16, i32::from(AF_INET6)), - Some(IpAddr::from(HOME6)) - ); - // Lengths and families that cannot carry an address. - assert_eq!(raw_ip(HOME.as_ptr().cast(), 3, i32::from(AF_INET)), None); - assert_eq!(raw_ip(HOME6.as_ptr().cast(), 15, i32::from(AF_INET6)), None); - assert_eq!(raw_ip(HOME.as_ptr().cast(), 4, 99), None); - assert_eq!(raw_ip(HOME.as_ptr().cast(), -4, i32::from(AF_INET)), None); - assert_eq!(raw_ip(std::ptr::null(), 4, i32::from(AF_INET)), None); - // A longer buffer still reads the address at its start. - let mut long = [0u8; 16]; - long[..4].copy_from_slice(&AWAY); - assert_eq!( - raw_ip(long.as_ptr().cast(), 16, i32::from(AF_INET)), - Some(IpAddr::from(AWAY)) - ); - } - - #[test] - fn only_loopback_is_local() { - for ip in ["127.0.0.1", "127.0.0.2", "127.255.255.255"] { - assert!(loopback(ip.parse().unwrap()), "{ip}"); - } - for ip in [ - "0.0.0.0", - "126.255.255.255", - "128.0.0.1", - "192.0.2.1", - "::", - "::2", - "2001:db8::1", - ] { - assert!(!loopback(ip.parse().unwrap()), "{ip}"); - } - assert!(loopback("::1".parse().unwrap())); - // An IPv4-mapped loopback address is a loopback address. - assert!(loopback("::ffff:127.0.0.1".parse().unwrap())); - assert!(!loopback("::ffff:192.0.2.1".parse().unwrap())); - } - - #[test] - fn names_are_local_only_for_localhost_and_loopback_literals() { - for name in [ - "localhost", - "LocalHost", - "127.0.0.1", - "127.1.2.3", - "::1", - "[::1]", - "[::ffff:127.0.0.1]", - ] { - assert!(loopback_name(name), "{name}"); - } - for name in [ - "", - "example.com", - "localhost.example.com", - "192.0.2.1", - "0.0.0.0", - "::2", - "[::2]", - ] { - assert!(!loopback_name(name), "{name}"); - } - } - - #[test] - fn names_are_read_as_narrow_or_utf16() { - assert_eq!(narrow(std::ptr::null()), None); - assert_eq!(narrow(c"localhost".as_ptr()).as_deref(), Some("localhost")); - assert_eq!(narrow(c"".as_ptr()).as_deref(), Some("")); - // ANSI is not UTF-8: an odd byte becomes a replacement character, - // never part of a name that would match. - let ansi = [b'c', b'a', b'f', 0xe9, 0]; - assert_eq!(narrow(ansi.as_ptr().cast()).as_deref(), Some("caf\u{fffd}")); - - assert_eq!(wide(std::ptr::null()), None); - assert_eq!( - wide(utf16("localhost").as_ptr()).as_deref(), - Some("localhost") - ); - assert_eq!(wide(utf16("").as_ptr()).as_deref(), Some("")); - let unicode = "h\u{e9}llo/\u{65e5}\u{672c}"; - assert_eq!(wide(utf16(unicode).as_ptr()).as_deref(), Some(unicode)); - // A surrogate pair is one character, not two replacements. - assert_eq!( - wide(utf16("\u{1f680}").as_ptr()).as_deref(), - Some("\u{1f680}") - ); - } - - #[test] - fn lookups_answer_without_asking_the_network() { - up(); - assert!(resolvable(None)); - assert!(resolvable(Some(String::new()))); - assert!(resolvable(Some("localhost".into()))); - assert!(resolvable(Some("LocalHost".into()))); - assert!(resolvable(Some("127.0.0.1".into()))); - assert!(resolvable(Some("::1".into()))); - assert!(!resolvable(Some("example.com".into()))); assert_eq!(last_error(), WSAHOST_NOT_FOUND); + assert_eq!(connect(s, v4(HOME, port).as_ptr(), 16), 0); + listener.accept().unwrap(); + // A stream socket sends to its vetted peer whatever `to` says. + assert_eq!(sendto(s, b"x".as_ptr(), 1, 0, v4(AWAY, 9).as_ptr(), 16), 1); + close(s); - // Classifying does not touch the error: the caller sets it. - wsa_error(0); - assert!(reverse_resolvable(Some("127.0.0.1".parse().unwrap()))); - assert!(reverse_resolvable(Some("::1".parse().unwrap()))); - assert!(!reverse_resolvable(Some("192.0.2.1".parse().unwrap()))); - assert_eq!(last_error(), 0); - assert!(!reverse_resolvable(None)); - assert_eq!(last_error(), 0); - - let home = v4(HOME, 80); - let away = v4(AWAY, 80); - // No host wanted: nothing to decide. - assert_eq!(name_info_flags(home.as_ptr(), 16, false, 0), Some(0)); - // The numeric form is already local. - assert_eq!( - name_info_flags(home.as_ptr(), 16, true, NI_NUMERICHOST), - Some(NI_NUMERICHOST) - ); - // Loopback may be named; nothing else may. - assert_eq!(name_info_flags(home.as_ptr(), 16, true, 0), Some(0)); - assert_eq!( - name_info_flags(away.as_ptr(), 16, true, 0), - Some(NI_NUMERICHOST) - ); - assert_eq!( - name_info_flags(away.as_ptr(), 16, false, NI_NAMEREQD), - Some(NI_NAMEREQD) + // `ConnectEx` from `WSAIoctl` is the vetted one. + let s = socket(2, 1, 6); + let mut f = 0usize; + let mut size = 0u32; + let guid = WSAID_CONNECTEX; + let got = WSAIoctl( + s, + SIO_GET_EXTENSION_FUNCTION_POINTER, + (&raw const guid).cast(), + 16, + (&raw mut f).cast(), + 8, + &mut size, + null, + null, + ); + assert_eq!((got, f), (0, connect_ex as *const () as usize)); + assert_eq!( + connect_ex(s, v4(AWAY, 80).as_ptr(), 16, null, 0, n, null), + 0 ); - assert_eq!(name_info_flags(away.as_ptr(), 16, true, NI_NAMEREQD), None); - assert_eq!(last_error(), WSAHOST_NOT_FOUND); - } + assert_eq!(last_error(), WSAENETUNREACH); + close(s); - #[test] - fn a_bind_to_any_interface_is_narrowed_to_loopback() { - up(); - let socket = open(AF_INET, 2, 17); - assert_eq!( - bind(socket, v4([0, 0, 0, 0], 0).as_ptr(), 16), - 0, - "{}", - last_error() - ); - let (addr, len) = bound_address(socket); - assert_eq!(len, 16); - assert_eq!(&addr[4..8], &HOME); - // A port was picked, so the caller can bind and listen. - assert_ne!(addr[2], 0); - close(socket); - - // A loopback bind is passed through untouched. - let socket = open(AF_INET, 2, 17); - assert_eq!( - bind(socket, v4(HOME, 0).as_ptr(), 16), - 0, - "{}", - last_error() - ); - let (addr, _) = bound_address(socket); - assert_eq!(&addr[4..8], &HOME); - close(socket); - - // Anything else is not ours to bind. - let socket = open(AF_INET, 2, 17); - assert_eq!(bind(socket, v4(AWAY, 0).as_ptr(), 16), SOCKET_ERROR); - assert_eq!(last_error(), WSAEADDRNOTAVAIL); - assert_eq!(bind(socket, std::ptr::null(), 16), SOCKET_ERROR); - assert_eq!(last_error(), WSAEADDRNOTAVAIL); - close(socket); - - // `[::]` becomes `[::1]` the same way. - let Ok(listener) = std::net::UdpSocket::bind("[::1]:0") else { - return; - }; - drop(listener); - let socket = open(AF_INET6, 2, 17); + // Datagram sends. + let u = socket(2, 2, 17); assert_eq!( - bind(socket, v6([0; 16], 0).as_ptr(), 28), - 0, - "{}", - last_error() + sendto(u, b"x".as_ptr(), 1, 0, v4(AWAY, 9).as_ptr(), 16), + SOCKET_ERROR ); - let (addr, len) = bound_address(socket); - assert_eq!(len, 28); - assert_eq!(&addr[8..24], &HOME6); - close(socket); - } - - #[test] - fn connects_are_vetted_by_address() { - up(); - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - - let socket = open(AF_INET, 1, 6); - assert_eq!(connect(socket, v4(AWAY, 80).as_ptr(), 16), SOCKET_ERROR); - assert_eq!(last_error(), WSAENETUNREACH); - // No address at all is still no route. - assert_eq!(connect(socket, std::ptr::null(), 16), SOCKET_ERROR); assert_eq!(last_error(), WSAENETUNREACH); assert_eq!( - connect(socket, v4(HOME, port).as_ptr(), 16), - 0, - "{}", - last_error() + sendto(u, b"x".as_ptr(), 1, 0, v4(HOME, port).as_ptr(), 16), + 1 ); - listener.accept().unwrap(); - close(socket); + close(u); - let socket = open(AF_INET, 1, 6); + // Forward and reverse lookups. + let mut result = null; assert_eq!( - WSAConnect( - socket, - v4(AWAY, 80).as_ptr(), - 16, + getaddrinfo( + c"example.com".as_ptr(), std::ptr::null(), - std::ptr::null_mut(), std::ptr::null(), - std::ptr::null() + &mut result ), - SOCKET_ERROR + WSAHOST_NOT_FOUND ); - assert_eq!(last_error(), WSAENETUNREACH); - close(socket); - - // Joining a group is a connect for our purposes. - let socket = open(AF_INET, 2, 17); + let name: Vec = "example.com\0".encode_utf16().collect(); assert_eq!( - WSAJoinLeaf( - socket, - v4(AWAY, 80).as_ptr(), - 16, - std::ptr::null(), - std::ptr::null_mut(), + GetAddrInfoW( + name.as_ptr(), std::ptr::null(), std::ptr::null(), - 0 - ), - INVALID_SOCKET - ); - assert_eq!(last_error(), WSAENETUNREACH); - close(socket); - - let Ok(listener) = std::net::TcpListener::bind("[::1]:0") else { - return; - }; - let port = listener.local_addr().unwrap().port(); - let socket = open(AF_INET6, 1, 6); - assert_eq!(connect(socket, v6(AWAY6, 80).as_ptr(), 28), SOCKET_ERROR); - assert_eq!(last_error(), WSAENETUNREACH); - assert_eq!( - connect(socket, v6(HOME6, port).as_ptr(), 28), - 0, - "{}", - last_error() - ); - listener.accept().unwrap(); - close(socket); - } - - #[test] - fn connects_are_vetted_by_name() { - up(); - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - let service = std::ffi::CString::new(port.to_string()).unwrap(); - let wide_service = utf16(&port.to_string()); - let lengths: *mut u32 = std::ptr::null_mut(); - let null = std::ptr::null_mut::(); - - let socket = open(AF_INET, 1, 6); - // A name would need a lookup, an address a route. - assert_eq!( - WSAConnectByNameA( - socket, - c"example.com".as_ptr(), - c"80".as_ptr(), - lengths, - null, - lengths, - null, - null, - null + &mut result ), - 0 + WSAHOST_NOT_FOUND ); - assert_eq!(last_error(), WSAHOST_NOT_FOUND); + let mut text = [0 as c_char; 64]; + let away = v4(AWAY, 80); assert_eq!( - WSAConnectByNameA( - socket, - c"192.0.2.1".as_ptr(), - c"80".as_ptr(), - lengths, - null, - lengths, - null, - null, - null + getnameinfo( + away.as_ptr(), + 16, + text.as_mut_ptr(), + 64, + std::ptr::null_mut(), + 0, + 0 ), 0 ); - assert_eq!(last_error(), WSAENETUNREACH); - // `localhost` is the one name answered. + // SAFETY: NUL-terminated by `getnameinfo`. + let numeric = unsafe { CStr::from_ptr(text.as_ptr()) }; + assert_eq!(numeric.to_str(), Ok("192.0.2.1")); assert_eq!( - WSAConnectByNameA( - socket, - c"localhost".as_ptr(), - service.as_ptr(), - lengths, - null, - lengths, - null, - null, - null + getnameinfo( + away.as_ptr(), + 16, + text.as_mut_ptr(), + 64, + std::ptr::null_mut(), + 0, + NI_NAMEREQD ), - 1, - "{}", - last_error() + WSAHOST_NOT_FOUND ); - listener.accept().unwrap(); - close(socket); + assert!(gethostbyaddr(AWAY.as_ptr().cast(), 4, 2).is_null()); - let socket = open(AF_INET, 1, 6); - let name = utf16("example.com"); + // WinHTTP. + assert!(WinHttpConnect(null, name.as_ptr(), 443, 0).is_null()); + // SAFETY: no arguments. + let error = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + assert_eq!(error, ERROR_WINHTTP_CANNOT_CONNECT); assert_eq!( - WSAConnectByNameW( - socket, - name.as_ptr(), - wide_service.as_ptr(), - lengths, - null, - lengths, - null, - null, - null - ), - 0 + WinHttpGetProxyForUrlEx(null, name.as_ptr(), std::ptr::null(), 0), + ERROR_WINHTTP_AUTODETECTION_FAILED ); - assert_eq!(last_error(), WSAHOST_NOT_FOUND); - let name = utf16("192.0.2.1"); - assert_eq!( - WSAConnectByNameW( - socket, - name.as_ptr(), - wide_service.as_ptr(), - lengths, - null, - lengths, - null, - null, - null - ), - 0 - ); - assert_eq!(last_error(), WSAENETUNREACH); - let name = utf16("127.0.0.1"); - assert_eq!( - WSAConnectByNameW( - socket, - name.as_ptr(), - wide_service.as_ptr(), - lengths, - null, - lengths, - null, - null, - null - ), - 1, - "{}", - last_error() - ); - listener.accept().unwrap(); - close(socket); - - // Every candidate of a list must be loopback. - let home = [v4(HOME, port)]; - let away = [v4(AWAY, 80)]; - let socket = open(AF_INET, 1, 6); - let list = address_list(&home); - assert_eq!( - WSAConnectByList( - socket, - list.as_ptr().cast(), - lengths, - null, - lengths, - null, - null, - null - ), - 1, - "{}", - last_error() - ); - listener.accept().unwrap(); - close(socket); - - let socket = open(AF_INET, 1, 6); - let list = address_list(&away); - assert_eq!( - WSAConnectByList( - socket, - list.as_ptr().cast(), - lengths, - null, - lengths, - null, - null, - null - ), - 0 - ); - assert_eq!(last_error(), WSAENETUNREACH); - close(socket); - - // One remote candidate spoils the list, before anything connects. - let mixed = [v4(HOME, port), v4(AWAY, 80)]; - let socket = open(AF_INET, 1, 6); - let list = address_list(&mixed); - assert_eq!( - WSAConnectByList( - socket, - list.as_ptr().cast(), - lengths, - null, - lengths, - null, - null, - null - ), - 0 - ); - assert_eq!(last_error(), WSAENETUNREACH); - listener.set_nonblocking(true).unwrap(); - assert!(listener.accept().is_err(), "a blocked list connected"); - close(socket); - - // A count the host cannot honour is refused, not vetted into a pass. - let mut negative = address_list(&away); - negative[0] = u64::from(u32::MAX); - let socket = open(AF_INET, 1, 6); - assert_eq!( - WSAConnectByList( - socket, - negative.as_ptr().cast(), - lengths, - null, - lengths, - null, - null, - null - ), - 0 - ); - close(socket); - } - - #[test] - fn connect_ex_and_send_msg_come_from_the_hle() { - up(); - let socket = open(AF_INET, 1, 6); - let null = std::ptr::null_mut::(); - let mut returned = 0u32; - - let connect_guid = WSAID_CONNECTEX; - let mut pointer = 0usize; - assert_eq!( - WSAIoctl( - socket, - SIO_GET_EXTENSION_FUNCTION_POINTER, - (&raw const connect_guid).cast(), - 16, - (&raw mut pointer).cast(), - 8, - &mut returned, - null, - null - ), - 0, - "{}", - last_error() - ); - assert_eq!(pointer, connect_ex as *const () as usize); - - let send_msg_guid = WSAID_WSASENDMSG; - assert_eq!( - WSAIoctl( - socket, - SIO_GET_EXTENSION_FUNCTION_POINTER, - (&raw const send_msg_guid).cast(), - 16, - (&raw mut pointer).cast(), - 8, - &mut returned, - null, - null - ), - 0, - "{}", - last_error() - ); - assert_eq!(pointer, WSASendMsg as *const () as usize); - // The multi-pointer query (Registered I/O) is refused as by an old - // system, before any argument is looked at. - assert_eq!( - WSAIoctl( - socket, - SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER, - (&raw const connect_guid).cast(), - 16, - (&raw mut pointer).cast(), - 8, - &mut returned, - null, - null - ), - SOCKET_ERROR - ); - assert_eq!(last_error(), WSAEINVAL); - assert_eq!( - WSAIoctl( - INVALID_SOCKET, - SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER, - std::ptr::null(), - 0, - std::ptr::null_mut(), - 0, - std::ptr::null_mut(), - null, - null - ), - SOCKET_ERROR - ); - assert_eq!(last_error(), WSAEINVAL); - - // A GUID we do not know is the host's pointer, or its refusal. - let foreign = Guid(0, 0, 0, [0; 8]); - let mut untouched = 0usize; - assert_ne!( - WSAIoctl( - socket, - SIO_GET_EXTENSION_FUNCTION_POINTER, - (&raw const foreign).cast(), - 16, - (&raw mut untouched).cast(), - 8, - &mut returned, - null, - null - ), - 0 - ); - assert_eq!(untouched, 0); - - // A short output buffer or a short input is never written to. - let mut small = 0u32; - assert_ne!( - WSAIoctl( - socket, - SIO_GET_EXTENSION_FUNCTION_POINTER, - (&raw const send_msg_guid).cast(), - 16, - (&raw mut small).cast(), - 4, - &mut returned, - null, - null - ), - 0 - ); - assert_eq!(small, 0); - let mut pointer = usize::MAX; - assert_ne!( - WSAIoctl( - socket, - SIO_GET_EXTENSION_FUNCTION_POINTER, - (&raw const send_msg_guid).cast(), - 15, - (&raw mut pointer).cast(), - 8, - &mut returned, - null, - null - ), - 0 - ); - assert_eq!(pointer, usize::MAX); - - // The `ConnectEx` handed out is the vetted one. - assert_eq!( - connect_ex( - socket, - v4(AWAY, 80).as_ptr(), - 16, - std::ptr::null(), - 0, - std::ptr::null_mut(), - null - ), - 0 - ); - assert_eq!(last_error(), WSAENETUNREACH); - close(socket); - } - - #[test] - fn datagrams_to_the_network_are_dropped() { - up(); - let listener = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); - listener - .set_read_timeout(Some(std::time::Duration::from_millis(500))) - .unwrap(); - let port = listener.local_addr().unwrap().port(); - let home = v4(HOME, port); - let away = v4(AWAY, 9); - let mut got = [0u8; 8]; - - let socket = open(AF_INET, 2, 17); - assert_eq!( - sendto(socket, b"x".as_ptr(), 1, 0, away.as_ptr(), 16), - SOCKET_ERROR - ); - assert_eq!(last_error(), WSAENETUNREACH); - assert!( - listener.recv_from(&mut got).is_err(), - "a blocked datagram arrived" - ); - assert_eq!( - sendto(socket, b"x".as_ptr(), 1, 0, home.as_ptr(), 16), - 1, - "{}", - last_error() - ); - assert_eq!(listener.recv_from(&mut got).unwrap().0, 1); - close(socket); - - let socket = open(AF_INET, 2, 17); - let mut payload = *b"y"; - let buffers = [WsaBuf { - len: 1, - buf: payload.as_mut_ptr(), - }]; - let mut sent = 0u32; - assert_eq!( - WSASendTo( - socket, - buffers.as_ptr().cast(), - 1, - &mut sent, - 0, - away.as_ptr(), - 16, - std::ptr::null_mut(), - std::ptr::null() - ), - SOCKET_ERROR - ); - assert_eq!(last_error(), WSAENETUNREACH); - assert!( - listener.recv_from(&mut got).is_err(), - "a blocked datagram arrived" - ); - assert_eq!( - WSASendTo( - socket, - buffers.as_ptr().cast(), - 1, - &mut sent, - 0, - home.as_ptr(), - 16, - std::ptr::null_mut(), - std::ptr::null() - ), - 0, - "{}", - last_error() - ); - assert_eq!(sent, 1); - assert_eq!(listener.recv_from(&mut got).unwrap().0, 1); - close(socket); - - let socket = open(AF_INET, 2, 17); - let mut payload = *b"z"; - let buffers = [WsaBuf { - len: 1, - buf: payload.as_mut_ptr(), - }]; - let mut msg = WsaMsg { - name: away.as_ptr(), - namelen: 16, - buffers: buffers.as_ptr(), - count: 1, - control: WsaBuf { - len: 0, - buf: std::ptr::null_mut(), - }, - flags: 0, - }; - let mut sent = 0u32; - assert_eq!( - WSASendMsg( - socket, - (&raw const msg).cast(), - 0, - &mut sent, - std::ptr::null_mut(), - std::ptr::null() - ), - SOCKET_ERROR - ); - assert_eq!(last_error(), WSAENETUNREACH); - assert!( - listener.recv_from(&mut got).is_err(), - "a blocked datagram arrived" - ); - msg.name = home.as_ptr(); - assert_eq!( - WSASendMsg( - socket, - (&raw const msg).cast(), - 0, - &mut sent, - std::ptr::null_mut(), - std::ptr::null() - ), - 0, - "{}", - last_error() - ); - assert_eq!(sent, 1); - assert_eq!(listener.recv_from(&mut got).unwrap().0, 1); - close(socket); - - // A stream socket ignores `to`: the bytes reach the vetted peer. - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - let socket = open(AF_INET, 1, 6); - assert_eq!( - connect(socket, v4(HOME, port).as_ptr(), 16), - 0, - "{}", - last_error() - ); - let (mut peer, _) = listener.accept().unwrap(); - peer.set_read_timeout(Some(std::time::Duration::from_millis(500))) - .unwrap(); - assert_eq!(sendto(socket, b"s".as_ptr(), 1, 0, away.as_ptr(), 16), 1); - let mut byte = [0u8; 1]; - assert_eq!(std::io::Read::read(&mut peer, &mut byte).unwrap(), 1); - assert_eq!(byte, *b"s"); - let mut payload = *b"b"; - let buffers = [WsaBuf { - len: 1, - buf: payload.as_mut_ptr(), - }]; - let mut sent = 0u32; - assert_eq!( - WSASendTo( - socket, - buffers.as_ptr().cast(), - 1, - &mut sent, - 0, - away.as_ptr(), - 16, - std::ptr::null_mut(), - std::ptr::null() - ), - 0, - "{}", - last_error() - ); - assert_eq!(sent, 1); - assert_eq!(std::io::Read::read(&mut peer, &mut byte).unwrap(), 1); - assert_eq!(byte, *b"b"); - close(socket); - } - - #[test] - fn forward_lookups_only_answer_local_names() { - up(); - let mut result = std::ptr::null_mut(); - assert_eq!( - getaddrinfo( - c"example.com".as_ptr(), - std::ptr::null(), - std::ptr::null(), - &mut result - ), - WSAHOST_NOT_FOUND - ); - assert!(result.is_null()); - let name = utf16("example.com"); - assert_eq!( - GetAddrInfoW( - name.as_ptr(), - std::ptr::null(), - std::ptr::null(), - &mut result - ), - WSAHOST_NOT_FOUND - ); - assert_eq!( - GetAddrInfoExA( - c"example.com".as_ptr(), - std::ptr::null(), - 0, - std::ptr::null(), - std::ptr::null(), - &mut result, - std::ptr::null(), - std::ptr::null_mut(), - std::ptr::null(), - std::ptr::null_mut() - ), - WSAHOST_NOT_FOUND - ); - assert_eq!( - GetAddrInfoExW( - name.as_ptr(), - std::ptr::null(), - 0, - std::ptr::null(), - std::ptr::null(), - &mut result, - std::ptr::null(), - std::ptr::null_mut(), - std::ptr::null(), - std::ptr::null_mut() - ), - WSAHOST_NOT_FOUND - ); - - // A null name only asks about the machine itself. - assert_eq!( - getaddrinfo( - std::ptr::null(), - c"80".as_ptr(), - std::ptr::null(), - &mut result - ), - 0, - "{}", - last_error() - ); - assert!(!result.is_null()); - free_addrinfo(result, false); - - // `localhost` resolves, and to nothing but loopback. - let localhost = utf16("localhost"); - assert_eq!( - GetAddrInfoW( - localhost.as_ptr(), - std::ptr::null(), - std::ptr::null(), - &mut result - ), - 0, - "{}", - last_error() - ); - let mut count = 0; - let mut node = result.cast::(); - while !node.is_null() { - // SAFETY: an entry of the list the host just returned. - let info = unsafe { &*node }; - let addr = socket_addr(info.addr, info.addr_len as i32).expect("an address"); - assert!(loopback(addr.ip()), "{addr} is not loopback"); - count += 1; - node = info.next; - } - assert!(count > 0, "localhost resolved to nothing"); - free_addrinfo(result, true); - - assert!(gethostbyname(c"example.com".as_ptr()).is_null()); - assert_eq!(last_error(), WSAHOST_NOT_FOUND); - assert!(!gethostbyname(c"localhost".as_ptr()).is_null()); - let mut buf = [0 as c_char; 64]; - assert!( - WSAAsyncGetHostByName( - std::ptr::null_mut(), - 1, - c"example.com".as_ptr(), - buf.as_mut_ptr(), - 64 - ) - .is_null() - ); - assert_eq!(last_error(), WSAHOST_NOT_FOUND); - } - - #[test] - fn reverse_lookups_stay_numeric_or_fail() { - up(); - let away = v4(AWAY, 80); - let mut host_text = [0 as c_char; 64]; - assert_eq!( - getnameinfo( - away.as_ptr(), - 16, - host_text.as_mut_ptr(), - 64, - std::ptr::null_mut(), - 0, - 0 - ), - 0, - "{}", - last_error() - ); - assert_eq!(cstr(&host_text), "192.0.2.1"); - - // A name is required: nobody answers for it. - assert_eq!( - getnameinfo( - away.as_ptr(), - 16, - host_text.as_mut_ptr(), - 64, - std::ptr::null_mut(), - 0, - NI_NAMEREQD - ), - WSAHOST_NOT_FOUND - ); - // Unless the numeric form is asked for by name or by default. - assert_eq!( - getnameinfo( - away.as_ptr(), - 16, - host_text.as_mut_ptr(), - 64, - std::ptr::null_mut(), - 0, - NI_NAMEREQD | NI_NUMERICHOST - ), - 0, - "{}", - last_error() - ); - assert_eq!(cstr(&host_text), "192.0.2.1"); - - // The service half comes from a local table, so it answers alone. - let mut service = [0 as c_char; 16]; - assert_eq!( - getnameinfo( - away.as_ptr(), - 16, - std::ptr::null_mut(), - 0, - service.as_mut_ptr(), - 16, - 0 - ), - 0, - "{}", - last_error() - ); - assert!(!cstr(&service).is_empty()); - - let away6 = v6(AWAY6, 80); - let mut text6 = [0 as c_char; 64]; - assert_eq!( - getnameinfo( - away6.as_ptr(), - 28, - text6.as_mut_ptr(), - 64, - std::ptr::null_mut(), - 0, - 0 - ), - 0, - "{}", - last_error() - ); - assert!(cstr(&text6).contains("2001:db8")); - - // The wide variant reads the same address the same way. - let mut wide_text = [0u16; 64]; - assert_eq!( - GetNameInfoW( - away.as_ptr(), - 16, - wide_text.as_mut_ptr(), - 64, - std::ptr::null_mut(), - 0, - 0 - ), - 0, - "{}", - last_error() - ); - let end = wide_text.iter().position(|&c| c == 0).unwrap(); - assert_eq!(String::from_utf16(&wide_text[..end]).unwrap(), "192.0.2.1"); - - assert!(gethostbyaddr(AWAY.as_ptr().cast(), 4, i32::from(AF_INET)).is_null()); - assert_eq!(last_error(), WSAHOST_NOT_FOUND); - // Not an address of any family: still nothing to name. - assert!(gethostbyaddr(AWAY.as_ptr().cast(), 4, 99).is_null()); - assert_eq!(last_error(), WSAHOST_NOT_FOUND); - let mut buf = [0 as c_char; 64]; - assert!( - WSAAsyncGetHostByAddr( - std::ptr::null_mut(), - 1, - AWAY.as_ptr().cast(), - 4, - i32::from(AF_INET), - buf.as_mut_ptr(), - 64 - ) - .is_null() - ); - assert_eq!(last_error(), WSAHOST_NOT_FOUND); - } - - #[test] - fn name_space_queries_are_refused() { - up(); - let mut handle: Handle = std::ptr::null_mut(); - assert_eq!( - WSALookupServiceBeginA(std::ptr::null(), 0, &mut handle), - SOCKET_ERROR - ); - assert_eq!(last_error(), WSASERVICE_NOT_FOUND); - assert!(handle.is_null()); - assert_eq!( - WSALookupServiceBeginW(std::ptr::null(), 0, &mut handle), - SOCKET_ERROR - ); - assert_eq!(last_error(), WSASERVICE_NOT_FOUND); - assert!(handle.is_null()); - } - - #[test] - fn winhttp_only_reaches_the_machine() { - up(); - let close_handle = - host!("winhttp.dll", "WinHttpCloseHandle": extern "system" fn(Handle) -> i32); - let query = host!("winhttp.dll", "WinHttpQueryOption": extern "system" fn(Handle, u32, *mut c_void, *mut u32) -> i32); - - // A session opened with a named proxy still has none. - let proxy = utf16("192.0.2.1:8080"); - let session = WinHttpOpen(std::ptr::null(), 3, proxy.as_ptr(), std::ptr::null(), 0); - assert!(!session.is_null(), "{}", last_error_win32()); - let mut info = [0u8; 24]; - let mut len = info.len() as u32; - assert_eq!( - query( - session, - WINHTTP_OPTION_PROXY, - info.as_mut_ptr().cast(), - &mut len - ), - 1 - ); - assert_eq!( - u32::from_le_bytes([info[0], info[1], info[2], info[3]]), - WINHTTP_ACCESS_TYPE_NO_PROXY - ); - - // A proxy set later is accepted and not used. - #[repr(C)] - struct ProxyInfo { - access: u32, - proxy: *const u16, - bypass: *const u16, - } - let named = ProxyInfo { - access: 3, - proxy: proxy.as_ptr(), - bypass: std::ptr::null(), - }; - assert_eq!( - WinHttpSetOption( - session, - WINHTTP_OPTION_PROXY, - (&raw const named).cast(), - size_of::() as u32 - ), - 1 - ); - let mut len = info.len() as u32; - assert_eq!( - query( - session, - WINHTTP_OPTION_PROXY, - info.as_mut_ptr().cast(), - &mut len - ), - 1 - ); - assert_eq!( - u32::from_le_bytes([info[0], info[1], info[2], info[3]]), - WINHTTP_ACCESS_TYPE_NO_PROXY - ); - - // A handle nobody opened is the host's to refuse. - assert_eq!( - WinHttpSetOption( - std::ptr::null_mut(), - WINHTTP_OPTION_PROXY, - std::ptr::null(), - 0 - ), - 0 - ); - - // Loopback, by name or literal, gets a handle; nothing else does. - for server in ["localhost", "127.0.0.1"] { - let name = utf16(server); - let connection = WinHttpConnect(session, name.as_ptr(), 80, 0); - assert!(!connection.is_null(), "{server}: {}", last_error_win32()); - let _ = close_handle(connection); - } - for server in ["example.com", "192.0.2.1", "[::2]"] { - let name = utf16(server); - assert!( - WinHttpConnect(session, name.as_ptr(), 80, 0).is_null(), - "{server}" - ); - assert_eq!(last_error_win32(), ERROR_WINHTTP_CANNOT_CONNECT, "{server}"); - } - let _ = close_handle(session); - } - - #[test] - fn proxy_auto_detection_fails_like_an_unplugged_machine() { - up(); - let mut url: *mut u16 = std::ptr::null_mut(); - assert_eq!(WinHttpDetectAutoProxyConfigUrl(1, &mut url), 0); - assert_eq!(last_error_win32(), ERROR_WINHTTP_AUTODETECTION_FAILED); - assert!(url.is_null()); - - let page = utf16("http://example.com/"); - let mut info = [0u8; 24]; - assert_eq!( - WinHttpGetProxyForUrl( - std::ptr::null_mut(), - page.as_ptr(), - std::ptr::null(), - info.as_mut_ptr().cast() - ), - 0 - ); - assert_eq!(last_error_win32(), ERROR_WINHTTP_AUTODETECTION_FAILED); - assert_eq!( - WinHttpGetProxyForUrlEx(std::ptr::null_mut(), page.as_ptr(), std::ptr::null(), 0), - ERROR_WINHTTP_AUTODETECTION_FAILED - ); - assert_eq!( - WinHttpGetProxyForUrlEx2( - std::ptr::null_mut(), - page.as_ptr(), - std::ptr::null(), - 0, - std::ptr::null(), - 0 - ), - ERROR_WINHTTP_AUTODETECTION_FAILED - ); - assert_eq!( - WinHttpGetProxySettingsEx(std::ptr::null_mut(), 0, std::ptr::null(), 0), - ERROR_WINHTTP_AUTODETECTION_FAILED - ); - } - - #[test] - fn every_override_names_a_real_export() { // The ordinals we override name the functions they stand for. - let net = module(); - for entry in net.exports.iter().filter(|e| e.name.starts_with('#')) { - let named = net + let m = module(); + for e in m.exports.iter().filter(|e| e.name.starts_with('#')) { + let named = m .exports .iter() - .find(|n| n.address == entry.address && !n.name.starts_with('#')) + .find(|n| n.address == e.address && !n.name.starts_with('#')) .unwrap(); - let by_ordinal = ImportSymbol::Ordinal(entry.name[1..].parse().unwrap()); + let by_ordinal = ImportSymbol::Ordinal(e.name[1..].parse().unwrap()); assert_eq!( crate::HostPolicy::default().resolve("ws2_32.dll", &by_ordinal), crate::host::function("ws2_32.dll", named.name), "{} is not {}", - entry.name, + e.name, named.name ); } - // Every override names a real export of its DLL. Some exports the - // HLE supplies itself (Wine lacks them; WinHttpGetProxySettingsEx is - // absent even from Windows 10's winhttp.dll): skip each only when - // the host really lacks it. - const FALLBACK: &[&str] = &[ - "WSAConnectByList", - "GetAddrInfoExA", - "WinHttpGetProxySettingsEx", - ]; - for entry in net.exports.iter().filter(|e| !e.name.starts_with('#')) { - let dll = if entry.name.starts_with("WinHttp") { + // Every override names a real export of its DLL. Some exports only + // exist on newer Windows (WinHttpGetProxySettingsEx is absent from + // Windows 10's winhttp.dll); the HLE supplies those itself, so skip + // them only when the host really lacks them. + const NEWER_WINDOWS_ONLY: &[&str] = &["WinHttpGetProxySettingsEx"]; + for e in m.exports.iter().filter(|e| !e.name.starts_with('#')) { + let dll = if e.name.starts_with("WinHttp") { "winhttp.dll" } else { "ws2_32.dll" }; - let present = crate::host::function(dll, entry.name).is_some(); - if !present && FALLBACK.contains(&entry.name) { + let present = crate::host::function(dll, e.name).is_some(); + if !present && NEWER_WINDOWS_ONLY.contains(&e.name) { continue; } - assert!(present, "{dll} lacks {}", entry.name); + assert!(present, "{dll} lacks {}", e.name); } } } diff --git a/crates/victory-hle/src/modules/storage.rs b/crates/victory-hle/src/modules/storage.rs index 4b36c75..600cbad 100644 --- a/crates/victory-hle/src/modules/storage.rs +++ b/crates/victory-hle/src/modules/storage.rs @@ -26,7 +26,7 @@ pub const IID: Guid = Guid::new( [0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d], ); -/// As Grand Theft Auto VI (2026) asks for it; it calls 0x20 (path) and 0x28 +/// As the title (2026) asks for it; it calls 0x20 (path) and 0x28 /// (space) with the same arguments. pub const IID_2026: Guid = Guid::new( 0x41a4_e10c, @@ -174,17 +174,10 @@ static VTABLE: Methods<8> = Methods([ #[cfg(test)] mod tests { - #[cfg(windows)] use super::*; - #[cfg(windows)] use crate::modules::xgameruntime::method; - /// The drive-over-folder mount is a Windows-only path (the virtual - /// drives themselves live in the `files` module), so this test runs - /// on Windows only. - #[cfg(windows)] #[test] - #[cfg_attr(not(windows), ignore = "the title's file calls are Windows-only")] fn serves_a_drive_over_the_title_folder_and_its_quota() { type Size = extern "system" fn(This, *mut usize) -> HRESULT; type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT; @@ -212,17 +205,14 @@ mod tests { let drive = std::str::from_utf8(&buffer[..3]).unwrap(); assert!(drive.ends_with(":\\"), "{drive}"); // Title file calls on it reach the folder. - #[cfg(windows)] - { - let path = format!("{drive}save.dat\0"); - let mut attributes = [0u8; 36]; - let get_attributes = super::super::files::GetFileAttributesExW; - let wide: Vec = path.encode_utf16().collect(); - assert_ne!( - get_attributes(wide.as_ptr(), 0, attributes.as_mut_ptr().cast()), - 0 - ); - } + let path = format!("{drive}save.dat\0"); + let mut attributes = [0u8; 36]; + let get_attributes = super::super::files::GetFileAttributesExW; + let wide: Vec = path.encode_utf16().collect(); + assert_ne!( + get_attributes(wide.as_ptr(), 0, attributes.as_mut_ptr().cast()), + 0 + ); let mut info = SpaceInfo { available_free: 0, diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index f6b8921..068d75f 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -760,10 +760,7 @@ pub fn pending_with( identity: *const c_void, work: impl FnOnce() -> Result, HRESULT> + Send + 'static, ) -> HRESULT { - type Data = Mutex<( - Option Result, HRESULT> + Send>>, - Vec, - )>; + type Data = Mutex<(Option Result, HRESULT> + Send>>, Vec)>; extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { // SAFETY: the runtime passes valid provider data; the context is the // boxed state until cleanup frees it. @@ -774,11 +771,7 @@ pub fn pending_with( OP_CLEANUP => drop(unsafe { Box::from_raw(state) }), OP_BEGIN => { // SAFETY: as above; cleanup waits for completion. - let work = unsafe { &*state } - .lock() - .unwrap_or_else(|e| e.into_inner()) - .0 - .take(); + let work = unsafe { &*state }.lock().unwrap_or_else(|e| e.into_inner()).0.take(); let (block, state) = (data.block as usize, state as usize); std::thread::spawn(move || { let result = work.map_or(Err(E_ABORT), |work| work()); @@ -807,13 +800,7 @@ pub fn pending_with( } let state: Box = Box::new(Mutex::new((Some(Box::new(work)), Vec::new()))); let context = Box::into_raw(state); - let hr = XAsyncBegin( - block, - context.cast(), - identity, - std::ptr::null(), - Some(provider), - ); + let hr = XAsyncBegin(block, context.cast(), identity, std::ptr::null(), Some(provider)); if hr < 0 { // SAFETY: refused before the call existed; still ours. drop(unsafe { Box::from_raw(context) }); @@ -1177,13 +1164,7 @@ mod tests { }; let identity = 0x77 as *const c_void; assert_eq!( - XAsyncBegin( - &mut block, - std::ptr::null_mut(), - identity, - std::ptr::null(), - Some(provider) - ), + XAsyncBegin(&mut block, std::ptr::null_mut(), identity, std::ptr::null(), Some(provider)), S_OK ); assert!(XTaskQueueDispatch(q, WORK, 0)); @@ -1194,20 +1175,11 @@ mod tests { let mut value = 0u64; let mut used = 0; assert_eq!( - XAsyncGetResult( - &mut block, - identity, - 8, - (&mut value as *mut u64).cast(), - &mut used - ), + XAsyncGetResult(&mut block, identity, 8, (&mut value as *mut u64).cast(), &mut used), S_OK ); assert_eq!((value, used), (0x1234, 8)); - assert!( - call(&raw mut block).is_none(), - "the call ends with its result" - ); + assert!(call(&raw mut block).is_none(), "the call ends with its result"); XTaskQueueCloseHandle(q); } diff --git a/crates/victory-hle/src/modules/xg.rs b/crates/victory-hle/src/modules/xg.rs index d26d8c6..56011ec 100644 --- a/crates/victory-hle/src/modules/xg.rs +++ b/crates/victory-hle/src/modules/xg.rs @@ -3,7 +3,7 @@ //! slice lies, and to copy linear data into tiled memory and back. Served //! from `victory_formats::texture`. //! -//! Grand Theft Auto VI imports `XGCreateTextureComputer` and +//! The title imports `XGCreateTextureComputer` and //! `XGSuggestSwizzleMode` and calls these computer methods: Release (0x08), //! the layout (0x10), copies into (0x40) and out of (0x48) a subresource, //! and the 64 KiB tiling (0x50). The other slots log and fail. @@ -165,7 +165,7 @@ fn texture(desc: &ResourceDesc) -> Option { const MIPS: usize = 15; /// One mip in the layout the title reads (offsets 0x00, 0x08, 0x10 and -/// 0x1c are read by Grand Theft Auto VI; the rest follow the library's +/// 0x1c are read by the title; the rest follow the library's /// older public shape). #[repr(C)] #[derive(Debug, Default, Clone, Copy)] @@ -539,7 +539,7 @@ extern "system" fn tiling( } /// Slot 0x30 `(plane, mip, x, y, z or slice, sample, bit position)`: an -/// element's byte offset from the texture's start. Grand Theft Auto VI reads +/// element's byte offset from the texture's start. The title reads /// texels of a 128x4 `4KB_S` texture on the CPU through it (title+0x5151c90); /// an error returned as an offset made it read wild memory. 0 if outside. extern "system" fn element_offset( @@ -582,19 +582,19 @@ struct Vtable([*const (); 13]); unsafe impl Sync for Vtable {} static VTABLE: Vtable = Vtable([ - add_ref as *const (), // 0x00 - release as *const (), // 0x08 - layout as *const (), // 0x10 - unused as *const (), // 0x18 size - unused as *const (), // 0x20 alignment - unused as *const (), // 0x28 mip offset + add_ref as *const (), // 0x00 + release as *const (), // 0x08 + layout as *const (), // 0x10 + unused as *const (), // 0x18 size + unused as *const (), // 0x20 alignment + unused as *const (), // 0x28 mip offset element_offset as *const (), // 0x30 - unused as *const (), // 0x38 element coordinate - copy_into as *const (), // 0x40 - copy_from as *const (), // 0x48 - tiling as *const (), // 0x50 - unused as *const (), // 0x58 view descriptor - unused as *const (), // 0x60 tiled resource? + unused as *const (), // 0x38 element coordinate + copy_into as *const (), // 0x40 + copy_from as *const (), // 0x48 + tiling as *const (), // 0x50 + unused as *const (), // 0x58 view descriptor + unused as *const (), // 0x60 tiled resource? ]); pub(crate) fn module() -> HleModule { diff --git a/crates/victory-hle/src/modules/xgame.rs b/crates/victory-hle/src/modules/xgame.rs index 2cc4f5a..edcf2ea 100644 --- a/crates/victory-hle/src/modules/xgame.rs +++ b/crates/victory-hle/src/modules/xgame.rs @@ -63,8 +63,8 @@ extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT { } /// As documented: the title ends (suspended first, as on any end) and the -/// game starts again in a new process; this never returns. Grand Theft -/// Auto VI relaunches itself (its own path from `GetModuleFileNameA`) with +/// game starts again in a new process; this never returns. +/// The title relaunches itself (its own path from `GetModuleFileNameA`) with /// arguments from its configuration. The new `victory run` gets the same /// options, the new executable, and the title's arguments after `--` /// (the title reads the whole command line). @@ -74,28 +74,17 @@ extern "system" fn launch_new_game( args: *const c_char, _user: *const c_void, ) { - let (exe, args) = ( - text(exe).unwrap_or_default(), - text(args).unwrap_or_default(), - ); + let (exe, args) = (text(exe).unwrap_or_default(), text(args).unwrap_or_default()); tracing::info!(exe, args, "XLaunchNewGame"); let current = runtime::main_image() .and_then(runtime::image_path) .unwrap_or_default(); let ours: Vec<_> = std::env::args_os().skip(1).collect(); let command = relaunch_args(ours, current.as_os_str(), &exe, &args); - #[cfg(not(windows))] - let _ = command; - #[cfg(windows)] super::lifecycle::end_title( "XLaunchNewGame", Box::new(move || super::lifecycle::relaunch(command)), ); - #[cfg(not(windows))] - { - let _ = &command; - tracing::info!("XLaunchNewGame: not implemented on this host; the title ends"); - } loop { std::thread::park(); } @@ -206,32 +195,15 @@ mod tests { #[test] fn a_relaunch_keeps_our_options() { - let ours: Vec = [ - "run", - "G:/game.exe", - "--execute", - "--console", - "series-s", - "--", - "-old", - ] - .map(Into::into) - .into(); + let ours: Vec = + ["run", "G:/game.exe", "--execute", "--console", "series-s", "--", "-old"] + .map(Into::into) + .into(); let current = std::ffi::OsStr::new("G:/game.exe"); let again = relaunch_args(ours.clone(), current, "G:/game.exe", " -config=x -y "); - let expected = [ - "run", - "G:/game.exe", - "--execute", - "--console", - "series-s", - "--", - ]; + let expected = ["run", "G:/game.exe", "--execute", "--console", "series-s", "--"]; assert_eq!(again[..6], expected.map(std::ffi::OsString::from)); - assert_eq!( - again[6..], - ["-config=x", "-y"].map(std::ffi::OsString::from) - ); + assert_eq!(again[6..], ["-config=x", "-y"].map(std::ffi::OsString::from)); let other = relaunch_args(ours, current, "G:/other.exe", ""); assert_eq!(other.len(), 5); assert_eq!(other[1], "G:/other.exe"); diff --git a/crates/victory-hle/src/modules/xgameruntime.rs b/crates/victory-hle/src/modules/xgameruntime.rs index 8223bbd..b3f5963 100644 --- a/crates/victory-hle/src/modules/xgameruntime.rs +++ b/crates/victory-hle/src/modules/xgameruntime.rs @@ -141,8 +141,7 @@ pub fn put(out: *mut T, value: T) -> HRESULT { } /// Copies `text` and a NUL into the title's `size`-byte buffer and reports -/// the bytes used, as the runtime's string getters do. A buffer that does -/// not fit is left untouched. +/// the bytes used, as the runtime's string getters do. pub fn put_string(text: &str, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { let len = text.len() + 1; if buffer.is_null() || size < len { @@ -203,7 +202,7 @@ pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64) /// The stub prefers this one when present. It passes the same three values /// and a pointer to the title's initialisation options, null unless the -/// title initialises with options (Grand Theft Auto VI does not). +/// title initialises with options (the title does not). pub extern "system" fn InitializeApiImplEx2( version: u64, build: u64, @@ -219,8 +218,7 @@ pub extern "system" fn UninitializeApiImpl() { } /// The object for an implemented (provider, interface id); others fail, -/// each pair logged once. A null `out` is the title's own error, not a -/// missing area, and is neither logged nor remembered as one. +/// each pair logged once. pub extern "system" fn QueryApiImpl( provider: *const Guid, iid: *const Guid, @@ -232,9 +230,6 @@ pub extern "system" fn QueryApiImpl( else { return NOT_SUPPORTED; }; - if out.is_null() { - return xasync::E_INVALIDARG; - } #[cfg(feature = "diagnostics")] if tracing::enabled!(tracing::Level::DEBUG) { // Each runtime call site once: which title code uses which area, when. @@ -250,7 +245,9 @@ pub extern "system" fn QueryApiImpl( .iter() .flat_map(|area| area.iter()) .find(|(p, i, _)| (*p, *i) == (provider, iid)); - if let Some(&(_, _, object)) = found { + if let Some(&(_, _, object)) = found + && !out.is_null() + { // SAFETY: checked non-null; the title passes room for a pointer. unsafe { out.write((object as *const Object).cast_mut().cast()) }; return S_OK; @@ -295,258 +292,6 @@ mod tests { use super::*; use crate::modules::kernel::{FreeLibrary, GetProcAddress, LoadLibraryExA}; - fn first_interface() -> Interface { - AREAS[0][0] - } - - #[test] - fn the_error_codes_are_the_documented_ones() { - assert_eq!(S_OK, 0); - assert_eq!(NOT_SUPPORTED, 0x8007_0032_u32 as i32); - assert_eq!(xasync::E_NOTIMPL, 0x8000_4001_u32 as i32); - assert_eq!(xasync::E_INVALIDARG, 0x8007_0057_u32 as i32); - assert_eq!(xasync::E_NOT_SUFFICIENT_BUFFER, 0x8007_007A_u32 as i32); - } - - #[test] - fn a_guid_prints_the_canonical_form() { - let guid = Guid::new( - 0x0123_4567, - 0x89ab, - 0xcdef, - [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef], - ); - assert_eq!(guid.to_string(), "01234567-89ab-cdef-0123-456789abcdef"); - // Copy and equality: the table lookup compares pairs by value. - assert_eq!( - guid, - Guid::new(guid.data1, guid.data2, guid.data3, guid.data4) - ); - assert_ne!(guid, Guid::new(0, 0, 0, [0; 8])); - } - - #[test] - fn put_writes_through_a_valid_pointer_only() { - let mut count = 0xdead_beef_u32; - assert_eq!(put(&mut count, 7_u32), S_OK); - assert_eq!(count, 7); - let mut flag = false; - assert_eq!(put(&mut flag, true), S_OK); - assert!(flag); - let mut wide = 0_usize; - assert_eq!(put(&mut wide, usize::MAX), S_OK); - assert_eq!(wide, usize::MAX); - assert_eq!(put::(std::ptr::null_mut(), 1), xasync::E_INVALIDARG); - } - - #[test] - fn put_string_copies_the_text_and_its_nul() { - let mut buffer = [0xaa_u8; 8]; - let mut used = 0; - assert_eq!(put_string("abc", 4, buffer.as_mut_ptr(), &mut used), S_OK); - assert_eq!((used, &buffer[..5]), (4, &[b'a', b'b', b'c', 0, 0xaa][..])); - // An empty string still needs room for its NUL. - assert_eq!(put_string("", 1, buffer.as_mut_ptr(), &mut used), S_OK); - assert_eq!((used, buffer[0]), (1, 0)); - // The buffer's size, not the string's, decides what is written. - assert_eq!( - put_string("abc", 8, buffer.as_mut_ptr(), std::ptr::null_mut()), - S_OK - ); - assert_eq!(&buffer[..4], b"abc\0"); - } - - #[test] - fn put_string_refuses_what_it_cannot_fit() { - let mut buffer = [0xaa_u8; 4]; - let pointer = buffer.as_mut_ptr(); - let mut used = 0xdead_beef_usize; - for size in [3, 0] { - assert_eq!( - put_string("abc", size, pointer, &mut used), - xasync::E_NOT_SUFFICIENT_BUFFER, - "size {size}" - ); - } - assert_eq!( - put_string("abc", 4, std::ptr::null_mut(), &mut used), - xasync::E_NOT_SUFFICIENT_BUFFER - ); - assert_eq!( - put_string("abc", usize::MAX, std::ptr::null_mut(), &mut used), - xasync::E_NOT_SUFFICIENT_BUFFER - ); - assert_eq!(buffer, [0xaa; 4], "nothing is written on failure"); - assert_eq!(used, 0xdead_beef, "and no size is reported"); - } - - #[test] - fn text_reads_the_titles_strings() { - assert_eq!(text(std::ptr::null()), None); - assert_eq!(text(c"".as_ptr()).as_deref(), Some("")); - assert_eq!(text(c"Player".as_ptr()).as_deref(), Some("Player")); - // Not UTF-8: the bytes become replacement characters, never a panic. - assert_eq!(text(c"a\xffb".as_ptr()).as_deref(), Some("a\u{fffd}b")); - } - - #[test] - fn tokens_are_nonzero_and_distinct() { - let first = token(); - let second = token(); - assert!(first >= 1 && second > first); - let mut seen: Vec = (0..64).map(|_| token()).collect(); - seen.sort_unstable(); - seen.dedup(); - assert_eq!(seen.len(), 64); - assert!(!seen.contains(&0)); - } - - #[test] - fn every_registered_interface_answers_with_its_object() { - let mut pairs = Vec::new(); - for area in AREAS { - for &(provider, iid, object) in *area { - let mut out: *mut c_void = std::ptr::null_mut(); - assert_eq!( - QueryApiImpl(&provider, &iid, &mut out), - S_OK, - "{provider} {iid}" - ); - assert_eq!( - out as *const Object, object as *const Object, - "{provider} {iid}" - ); - assert!(!object.area.is_empty()); - pairs.push((provider.to_string(), iid.to_string())); - } - } - // A pair listed twice would leave one object unreachable. - let count = pairs.len(); - pairs.sort_unstable(); - pairs.dedup(); - assert_eq!(pairs.len(), count); - } - - #[test] - fn an_unimplemented_area_is_unsupported_and_writes_nothing() { - let unknown = Guid::new(0xdead_beef, 0x1234, 0x5678, [0; 8]); - let untouched = 0x1234 as *mut c_void; - let mut out = untouched; - assert_eq!(QueryApiImpl(&unknown, &unknown, &mut out), NOT_SUPPORTED); - // Again, to exercise the once-only log path. - assert_eq!(QueryApiImpl(&unknown, &unknown, &mut out), NOT_SUPPORTED); - let (provider, _, _) = first_interface(); - assert_eq!(QueryApiImpl(&provider, &unknown, &mut out), NOT_SUPPORTED); - assert_eq!(QueryApiImpl(&unknown, &provider, &mut out), NOT_SUPPORTED); - assert_eq!(out, untouched, "the output is not written on failure"); - // Null GUID pointers are tolerated, never dereferenced. - assert_eq!( - QueryApiImpl(std::ptr::null(), std::ptr::null(), &mut out), - NOT_SUPPORTED - ); - assert_eq!( - QueryApiImpl(std::ptr::null(), &unknown, &mut out), - NOT_SUPPORTED - ); - assert_eq!( - QueryApiImpl(&unknown, std::ptr::null(), &mut out), - NOT_SUPPORTED - ); - assert_eq!(out, untouched); - } - - #[test] - fn a_null_output_is_the_titles_argument_error() { - let (provider, iid, object) = first_interface(); - assert_eq!( - QueryApiImpl(&provider, &iid, std::ptr::null_mut()), - xasync::E_INVALIDARG, - "an implemented area with nowhere to put its object" - ); - // Argument validation comes first, whatever the pair names: a null - // output is not a missing area and must not be remembered as one. - let unknown = Guid::new(0xdead_beef, 0x1234, 0x5678, [0; 8]); - assert_eq!( - QueryApiImpl(&unknown, &unknown, std::ptr::null_mut()), - xasync::E_INVALIDARG - ); - // The same query still answers once there is room for the object. - let mut out: *mut c_void = std::ptr::null_mut(); - assert_eq!(QueryApiImpl(&provider, &iid, &mut out), S_OK); - assert_eq!(out as *const Object, object as *const Object); - } - - extern "system" fn answer(_: *const Object) -> u32 { - 7 - } - - static TEST_METHODS: Methods<4> = Methods([ - missing::<0> as *const (), - add_ref as *const (), - answer as *const (), - missing::<3> as *const (), - ]); - static TEST_OBJECT: Object = Object::new("test", &TEST_METHODS); - - #[test] - fn an_object_points_at_its_method_table() { - assert_eq!(TEST_OBJECT.vtable, TEST_METHODS.0.as_ptr()); - assert_eq!(TEST_OBJECT.area, "test"); - type Slot = extern "system" fn(*const Object) -> u32; - assert_eq!(method::(&TEST_OBJECT, 0x08)(&TEST_OBJECT), 1); - assert_eq!(method::(&TEST_OBJECT, 0x10)(&TEST_OBJECT), 7); - // Reference counting is a no-op: the tables are static, so a null - // handle is harmless too. - assert_eq!(add_ref(std::ptr::null()), 1); - let not_implemented = xasync::E_NOTIMPL as u32; - assert_eq!( - method::(&TEST_OBJECT, 0x00)(&TEST_OBJECT), - not_implemented - ); - assert_eq!( - method::(&TEST_OBJECT, 0x18)(&TEST_OBJECT), - not_implemented - ); - } - - #[test] - fn the_runtime_initialises_and_uninitialises() { - assert_eq!(XGameRuntimeInitialize(), S_OK); - assert_eq!(InitializeApiImpl(1, 2), S_OK); - assert_eq!(InitializeApiImplEx(1, 2, 3), S_OK); - assert_eq!(InitializeApiImplEx2(1, 2, 3, std::ptr::null()), S_OK); - let options = [0_u8; 16]; - assert_eq!(InitializeApiImplEx2(0, 0, 0, options.as_ptr().cast()), S_OK); - UninitializeApiImpl(); - XGameRuntimeUninitialize(); - // Reporting an error is a log: a null message is fine. - XErrorReport(S_OK, std::ptr::null()); - XErrorReport(xasync::E_INVALIDARG, c"bad argument".as_ptr()); - } - - #[test] - fn the_module_serves_the_runtime_dll() { - let module = module(); - assert_eq!(module.name, "xgameruntime"); - assert!(module.serves("XGAMERUNTIME.DLL")); - assert!(!module.serves("xgame.dll")); - let names: Vec<_> = module.exports.iter().map(|export| export.name).collect(); - assert_eq!( - names, - [ - "XGameRuntimeInitialize", - "XGameRuntimeUninitialize", - "InitializeApiImpl", - "InitializeApiImplEx", - "InitializeApiImplEx2", - "UninitializeApiImpl", - "QueryApiImpl", - "XErrorReport", - ] - ); - assert!(module.exports.iter().all(|export| export.address != 0)); - } - #[test] fn title_stub_loads_the_runtime_dynamically() { let load = |name: &CStr| LoadLibraryExA(name.as_ptr().cast(), std::ptr::null_mut(), 0x800); diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index 50bafd5..560b6a6 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -37,7 +37,7 @@ pub const PROVIDER: Guid = Guid::new( 0x4cc2, [0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2], ); -/// As Grand Theft Auto VI (2026) asks for it; every slot it calls takes +/// As the title (2026) asks for it; every slot it calls takes /// the public API's arguments in the same order as under the provider's /// own id (older titles). pub const IID_2026: Guid = Guid::new( @@ -256,9 +256,8 @@ fn commit( match source { Source::Data(data) => write(path, data)?, // Files are never changed in place, so sharing one is safe. - Source::Kept(from) => { - std::fs::hard_link(from, &path).or_else(|_| std::fs::copy(from, &path).map(drop))? - } + Source::Kept(from) => std::fs::hard_link(from, &path) + .or_else(|_| std::fs::copy(from, &path).map(drop))?, } step(); } @@ -461,9 +460,7 @@ impl Update { } let replaced: u64 = current.as_ref().map_or(0, |v| { let sizes = v.sizes(); - let changed = sizes - .iter() - .filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n)); + let changed = sizes.iter().filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n)); changed.map(|(_, size)| size).sum() }); let root = self.dir.parent().unwrap_or(&self.dir); @@ -516,11 +513,7 @@ fn read(c: &Container, names: Option>) -> Result bool, - context: *mut c_void, - callback: ContainerCallback, -) { +fn report(root: &Path, keep: impl Fn(&str) -> bool, context: *mut c_void, callback: ContainerCallback) { let infos: Vec<(CString, CString, u32, u64, i64)> = { let _saves = saves_lock(); containers(root) @@ -986,10 +974,7 @@ mod tests { fn a_full_disk_is_not_the_quota() { let mb = 1 << 20; assert_eq!(no_room(2 * mb, 0, 0, mb), Some(OUT_OF_LOCAL_STORAGE)); - assert_eq!( - no_room(2 * mb, 0, QUOTA - mb, 100 * mb), - Some(QUOTA_EXCEEDED) - ); + assert_eq!(no_room(2 * mb, 0, QUOTA - mb, 100 * mb), Some(QUOTA_EXCEEDED)); // Replacing a blob of the same size fits a full quota. assert_eq!(no_room(mb, mb, QUOTA, 100 * mb), None); assert_eq!(no_room(mb, 0, 0, mb), None); @@ -1018,28 +1003,18 @@ mod tests { } fn old_state() -> Option<(String, Vec<(String, String)>)> { - Some(( - "one".into(), - vec![("a".into(), "old a".into()), ("b".into(), "old b".into())], - )) + Some(("one".into(), vec![("a".into(), "old a".into()), ("b".into(), "old b".into())])) } /// Run by the crash test in a child process; does nothing otherwise. #[test] fn crash_child() { - let (Ok(root), Ok(op)) = ( - std::env::var("VICTORY_SAVE_CHILD"), - std::env::var("VICTORY_SAVE_OP"), - ) else { + let (Ok(root), Ok(op)) = (std::env::var("VICTORY_SAVE_CHILD"), std::env::var("VICTORY_SAVE_OP")) else { return; }; let root = PathBuf::from(root); let hr = if op == "update" { - update( - &root, - "two", - &[("a", Some("new a")), ("b", None), ("c", Some("new c"))], - ) + update(&root, "two", &[("a", Some("new a")), ("b", None), ("c", Some("new c"))]) } else { delete(&root, "Slot") }; @@ -1052,25 +1027,15 @@ mod tests { /// new one. #[test] fn a_kill_at_any_step_leaves_old_or_new() { - let new = Some(( - "two".into(), - vec![("a".into(), "new a".into()), ("c".into(), "new c".into())], - )); + let new = Some(("two".into(), vec![("a".into(), "new a".into()), ("c".into(), "new c".into())])); for (op, after) in [("update", new), ("delete", None)] { let mut seen = (0, 0); for stop in 1.. { let dir = tempfile::tempdir().unwrap(); let root = dir.path(); - assert_eq!( - update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), - S_OK - ); + assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK); let mut child = std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "modules::xgamesave::tests::crash_child", - "--nocapture", - ]) + .args(["--exact", "modules::xgamesave::tests::crash_child", "--nocapture"]) .args(["--test-threads=1"]) .env("VICTORY_SAVE_CHILD", root) .env("VICTORY_SAVE_OP", op) @@ -1115,35 +1080,16 @@ mod tests { for good in ["Profile/Slot_1", "a/b/Save-2.sav", "x", &"a".repeat(256)] { assert!(valid_container(good), "{good}"); } - for bad in [ - "a b", - "", - "a/", - "a.", - "a..b", - "a.b/c", - "a-b/c", - &"a".repeat(257), - ] { + for bad in ["a b", "", "a/", "a.", "a..b", "a.b/c", "a-b/c", &"a".repeat(257)] { assert!(!valid_container(bad), "{bad}"); } // Containers and blobs differing only in case, reserved device // names, characters the host forbids, long names: all distinct. let dir = tempfile::tempdir().unwrap(); - let p = Provider { - root: dir.path().into(), - }; + let p = Provider { root: dir.path().into() }; let long = "n".repeat(300); - let blobs = [ - "A", - "a", - "CON", - "nul.txt", - "x/y:z*?\"<>|", - long.as_str(), - "end. ", - ]; + let blobs = ["A", "a", "CON", "nul.txt", "x/y:z*?\"<>|", long.as_str(), "end. "]; for container in ["Save", "save", "SAVE/CON.x"] { let c = p.container(container); let u = Update { @@ -1175,10 +1121,7 @@ mod tests { #[test] fn the_old_layout_moves_over() { let saves = tempfile::tempdir().unwrap(); - let root = saves - .path() - .join(format!("{:016X}", xuser::XUID)) - .join("scid"); + let root = saves.path().join(format!("{:016X}", xuser::XUID)).join("scid"); let old = root.join("Player"); std::fs::create_dir_all(&old).unwrap(); std::fs::write(old.join("Save%20Game%20Data"), b"data").unwrap(); @@ -1271,10 +1214,7 @@ mod tests { S_OK ); type Delete = extern "system" fn(This, *mut Update, *const c_char) -> HRESULT; - assert_eq!( - method::(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), - S_OK - ); + assert_eq!(method::(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), S_OK); type Submit = extern "system" fn(This, *const Update, *mut AsyncBlock) -> HRESULT; let mut b = block(); assert_eq!(method::(&OBJECT, 0xe0)(this, update, &mut b), S_OK); diff --git a/crates/victory-hle/src/modules/xgameui.rs b/crates/victory-hle/src/modules/xgameui.rs index 642e455..9882b2e 100644 --- a/crates/victory-hle/src/modules/xgameui.rs +++ b/crates/victory-hle/src/modules/xgameui.rs @@ -18,7 +18,7 @@ pub const PROVIDER: Guid = Guid::new( 0x4043, [0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0], ); -/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x38, +/// As the title (2026) asks for it; the slots it calls (0x38, /// 0x40, 0x88-0x98) take the public API's arguments in the 2020 order. pub const IID_2026: Guid = Guid::new( 0xeaf6_69df, @@ -49,7 +49,7 @@ extern "system" fn profile_card_result(_: This, block: *mut AsyncBlock) -> HRESU xasync::XAsyncGetResult(block, (&raw const PROFILE).cast(), 0, none, none.cast()) } -/// Grand Theft Auto VI treats `E_ABORT` as cancelled and goes on; any +/// The title treats `E_ABORT` as cancelled and goes on; any /// other failure as an error. extern "system" fn text_entry_async( _: This, @@ -60,8 +60,7 @@ extern "system" fn text_entry_async( _scope: u32, max_length: u32, ) -> HRESULT { - let [title, description, default] = - [title, description, default].map(|t| text(t).unwrap_or_default()); + let [title, description, default] = [title, description, default].map(|t| text(t).unwrap_or_default()); tracing::info!(title, description, max_length, "text entry"); xasync::pending_with(block, (&raw const TEXT).cast(), move || { match ask(&title, &description, &default, max_length) { @@ -112,17 +111,11 @@ fn limit(typed: &str, max: u32) -> String { } /// Asks the user in a modal host dialog; `None` if dismissed. -#[cfg(all(windows, not(test)))] +#[cfg(not(test))] fn ask(title: &str, description: &str, default: &str, max: u32) -> Option { dialog::ask(title, description, default, max) } -/// No host dialog yet: as if the user dismissed it. -#[cfg(all(not(windows), not(test)))] -fn ask(_: &str, _: &str, _: &str, _: u32) -> Option { - None -} - /// Tests answer for the user: "typed" for a title starting with "Type", /// cancelled otherwise. #[cfg(test)] @@ -130,7 +123,6 @@ fn ask(title: &str, _: &str, default: &str, _: u32) -> Option { title.starts_with("Type").then(|| format!("{default}typed")) } -#[cfg(windows)] mod dialog { use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM}; use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; @@ -186,13 +178,7 @@ mod dialog { let ok = wm::BS_DEFPUSHBUTTON as u32 | tab; item(ok, [129, 40, 50, 14], wm::IDOK as u16, button, "OK"); let cancel = wm::BS_PUSHBUTTON as u32 | tab; - item( - cancel, - [183, 40, 50, 14], - wm::IDCANCEL as u16, - button, - "Cancel", - ); + item(cancel, [183, 40, 50, 14], wm::IDCANCEL as u16, button, "Cancel"); // The template must start on a DWORD. let template: Vec = t .chunks(2) @@ -213,12 +199,7 @@ mod dialog { entry.typed } - extern "system" fn procedure( - dialog: HWND, - message: u32, - wparam: WPARAM, - lparam: LPARAM, - ) -> isize { + extern "system" fn procedure(dialog: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> isize { // SAFETY: our dialog; its user data is the `Entry` from `ask`, // stored at WM_INITDIALOG. unsafe { @@ -233,16 +214,12 @@ mod dialog { 0 // focus set here } wm::WM_COMMAND => { - let entry = - &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry); + let entry = &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry); match (wparam & 0xffff) as i32 { wm::IDOK => { - let mut buffer = - vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1]; - let n = - wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32); - entry.typed = - Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize])); + let mut buffer = vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1]; + let n = wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32); + entry.typed = Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize])); wm::EndDialog(dialog, 1); } wm::IDCANCEL => { @@ -318,29 +295,19 @@ mod tests { u32, ) -> HRESULT; type Size = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; - type Result_ = - extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT; + type Result_ = extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT; let null = std::ptr::null(); let entry = method::(&OBJECT, 0x88); // Dismissed: cancelled. let mut b = block(); - assert_eq!( - entry(this, &mut b, c"Name".as_ptr(), null, null, 0, 16), - S_OK - ); + assert_eq!(entry(this, &mut b, c"Name".as_ptr(), null, null, 0, 16), S_OK); assert_eq!(xasync::XAsyncGetStatus(&mut b, true), E_ABORT); let mut size = 0; - assert_eq!( - method::(&OBJECT, 0x90)(this, &mut b, &mut size), - E_ABORT - ); + assert_eq!(method::(&OBJECT, 0x90)(this, &mut b, &mut size), E_ABORT); // Typed: the text, cut to the limit, with its NUL. let mut b = block(); let default = c"abc".as_ptr(); - assert_eq!( - entry(this, &mut b, c"Type".as_ptr(), null, default, 0, 6), - S_OK - ); + assert_eq!(entry(this, &mut b, c"Type".as_ptr(), null, default, 0, 6), S_OK); assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); assert_eq!(method::(&OBJECT, 0x90)(this, &mut b, &mut size), S_OK); assert_eq!(size, 7); diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 3dd170d..5f717bf 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -67,14 +67,13 @@ const GRAPHICS: u64 = 3; const ADDRESS_32BIT: u64 = 4; /// The host's write watching (not in windows-sys' memory module). const MEM_WRITE_WATCH: u32 = 0x20_0000; -const MEM_COALESCE_PLACEHOLDERS: u32 = 0x1; /// The addresses XMem `flags` allow, first and last: the low 4 GiB for /// 32-bit memory; else from 4 GiB (kept for 32-bit requests, which the /// title's big pools would otherwise crowd out) up to 46 down to 40 bits /// from the field at bit 12, or 40 bits without one: the console keeps -/// title memory there, and its ray-tracing structures must be (Grand Theft -/// Auto VI's BVH builder refuses one above; the title asks for its GPU heap +/// title memory there, and its ray-tracing structures must be ( +/// the title's BVH builder refuses one above; the title asks for its GPU heap /// with no field). Decision 0001. fn address_range(flags: u64) -> (usize, usize) { let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) { @@ -109,7 +108,7 @@ pub extern "system" fn XMemVirtualAlloc( // A reservation of 64 KiB pages takes physical pages later // (`XMemMapPhysicalPages`); on the host only a placeholder can. // shortcut: committing part of such a reservation later would fail - // (Grand Theft Auto VI's 23 calls never do); replace that part of the + // (the title's 23 calls never do); replace that part of the // placeholder then. let placeholder = kind & PAGES_64K == PAGES_64K && kind & MEM_COMMIT == 0; if placeholder { @@ -177,7 +176,7 @@ pub struct BasicInformation { } // shortcut: every committed page reports graphics memory and no tag, since -// all of it is GPU-reachable here (Grand Theft Auto VI's BVH builder, the +// all of it is GPU-reachable here (the title's BVH builder, the // only caller, wants graphics memory); remember the flags of // `XMemVirtualAlloc` regions if a title tells CPU-only memory apart. pub extern "system" fn XMemVirtualQuery( @@ -222,7 +221,7 @@ type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void; type FreeRoutine = extern "system" fn(*mut c_void, u64); /// The allocation and free routines the title's exe exports as -/// `__XMemAllocationHooks__` (Grand Theft Auto VI does): `XMemAlloc` and +/// `__XMemAllocationHooks__` (the title does): `XMemAlloc` and /// `XMemFree` call them, for the title's own calls and its middleware's; /// the `…Default` exports do not. fn hooks() -> [usize; 2] { @@ -292,7 +291,7 @@ pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_ }; // shortcut: the host heap's addresses lie above 2^40, unlike the // console's; nothing seen builds ray-tracing structures in this memory - // (Grand Theft Auto VI uses its GPU heap). Sub-allocate from a + // (the title uses its GPU heap). Sub-allocate from a // reservation below 2^40 if one does. // SAFETY: the layout has a non-zero size. let block = unsafe { alloc(layout) }; @@ -385,65 +384,6 @@ fn physical() -> MutexGuard<'static, Physical> { PHYSICAL.lock().unwrap_or_else(|e| e.into_inner()) } -/// Every address a physical page shows at, and the page each mapped -/// address shows, for the GPU side's write guards (`victory_gpu` -/// `set_alias_lookup`): the title writes a page through one view (a pool) -/// while the GPU reads it through another (its tiled heap, `map_alias`), -/// and a read-only guard on one view does not see writes through the -/// other. Its lock is taken last (inside `PHYSICAL` and the guards' lock) -/// and nothing is called while it is held. -#[derive(Default)] -struct Aliases { - /// (section, page index) to the addresses showing it. - by_page: HashMap<(usize, usize), Vec>, - /// Address to (section, page index). - by_address: HashMap, -} - -static ALIASES: LazyLock> = LazyLock::new(Mutex::default); - -fn aliases() -> MutexGuard<'static, Aliases> { - ALIASES.lock().unwrap_or_else(|e| e.into_inner()) -} - -/// Notes `[base, base + len)` as showing `slice` and the slices after it -/// (`shown`), or as no longer showing them. -fn note_aliases(base: usize, len: usize, slice: &Slice, shown: bool) { - let section = Arc::as_ptr(&slice.section) as usize; - let mut a = aliases(); - for k in 0..len / PAGE { - let (at, key) = (base + k * PAGE, (section, slice.index + k)); - if shown { - if let Some(old) = a.by_address.insert(at, key) - && let Some(list) = a.by_page.get_mut(&old) - { - list.retain(|&x| x != at); - } - a.by_page.entry(key).or_default().push(at); - } else if a.by_address.get(&at) == Some(&key) { - a.by_address.remove(&at); - if let Some(list) = a.by_page.get_mut(&key) { - list.retain(|&x| x != at); - if list.is_empty() { - a.by_page.remove(&key); - } - } - } - } -} - -/// The other addresses showing the physical page mapped at page address -/// `at` (`victory_gpu`'s write guards). -fn other_views(at: usize, out: &mut Vec) { - let page = at - at % PAGE; - let a = aliases(); - if let Some(key) = a.by_address.get(&page) - && let Some(list) = a.by_page.get(key) - { - out.extend(list.iter().copied().filter(|&x| x != page)); - } -} - /// `count` is in and out (pages wanted, pages given); all or nothing here. pub extern "system" fn XMemAllocatePhysicalPages( flags: u64, @@ -459,7 +399,7 @@ pub extern "system" fn XMemAllocatePhysicalPages( return 0; }; // A pagefile-backed section of `size` bytes, its pages committed when - // first mapped or written (`commit`): Grand Theft Auto VI asks for 6.1 + // first mapped or written (`commit`): the title asks for 6.1 // GiB at once, which a busy host often cannot commit (error 1450). // SAFETY: plain section creation. let handle = unsafe { @@ -488,6 +428,9 @@ pub extern "system" fn XMemAllocatePhysicalPages( flags = format_args!("{flags:#x}"), "XMemAllocatePhysicalPages" ); + // For the GPU side's in-place census: only a committed section can be + // opened as a host heap. + victory_gpu::title_memory_section(handle as usize, size as u64, on_wine()); let section = Arc::new(Section(handle)); let mut physical = physical(); let first = physical.next_page; @@ -506,7 +449,7 @@ pub extern "system" fn XMemAllocatePhysicalPages( } /// Page numbers count 4 KiB frames, so a 64 KiB page's is a multiple of -/// 16: Grand Theft Auto VI keeps them as 21-bit `number >> 4` and rebuilds +/// 16: the title keeps them as 21-bit `number >> 4` and rebuilds /// them with `<< 4` (128 GiB of pages at most). const FRAMES: usize = PAGE >> 12; @@ -593,6 +536,12 @@ fn runs(pages: &[usize], offset: usize, len: usize) -> Option bool { + runs(pages, offset, len).is_some() +} + /// Copies `data` into physical pages, from `offset` bytes into the first, /// whether or not they are mapped anywhere (DirectStorage destinations). /// One view per run of consecutive pages, not one per page: each view @@ -656,6 +605,11 @@ pub extern "system" fn XMemMapPhysicalPages( ) -> *mut c_void { let base = address as usize; let mut physical = physical(); + // Until the pages are mapped again: `unmap` takes whole views away and + // maps what stays of them again, and a mapped view is a reservation + // until it is committed. A read of title memory in place must not fall + // into that gap (`victory_gpu::title_memory_remapping`). + let _changing = victory_gpu::title_memory_remapping(); unmap(&mut physical, base, n * PAGE); if pages.is_null() { return address; @@ -687,7 +641,7 @@ pub extern "system" fn XMemMapPhysicalPages( } /// One page at each address; null `pages`, or a page number 0, unmaps -/// (Grand Theft Auto VI passes 0 for addresses to clear). +/// (the title passes 0 for addresses to clear). pub extern "system" fn XMemMapPhysicalPagesScatter( addresses: *const *mut c_void, n: usize, @@ -715,120 +669,44 @@ pub extern "system" fn XMemMapPhysicalPagesScatter( 1 } -fn view_run(physical: &Physical, at: usize, max_len: usize) -> Option<(Slice, usize)> { - let (&base, &(size, ref s)) = physical - .views - .range(..=at) - .next_back() - .filter(|&(&base, &(size, _))| at < base + size)?; - let pages = ((base + size - at) / PAGE).min(max_len.div_ceil(PAGE)); - if pages == 0 { - return None; - } - Some(( - Slice { - index: s.index + (at - base) / PAGE, - section: s.section.clone(), - }, - pages * PAGE, - )) -} - /// Maps the physical pages shown at `[from, from + len)` at `to` as well, /// in place of what `to` shows; `from` 0 unmaps. The GPU's page-mapping -/// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`): Grand Theft Auto -/// VI maps pages into a pool view, then has the GPU map them into its tiled -/// heap. One view per run of consecutive slices of one section; false if a -/// source page is not mapped physical memory. +/// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`): +/// the title maps pages into a pool view, then has the GPU map them into its tiled +/// heap. Page by page; false if a source page is not mapped physical memory. pub fn map_alias(to: u64, from: u64, len: u64) -> bool { let (to, from, len) = (to as usize, from as usize, len as usize); let mut physical = physical(); + // As in `XMemMapPhysicalPages`: no read in place meets the gap. + let _changing = victory_gpu::title_memory_remapping(); unmap(&mut physical, to, len); - if from == 0 { - return true; - } - let mut k = 0; - while k < len { - let Some(at) = from.checked_add(k) else { + for k in (0..len).step_by(PAGE) { + if from == 0 { + break; + } + let at = from + k; + let Some(slice) = physical + .views + .range(..=at) + .next_back() + .filter(|(base, (size, _))| at < *base + size) + .map(|(base, (_, s))| Slice { + index: s.index + (at - base) / PAGE, + section: s.section.clone(), + }) + else { return false; }; - let Some((first, mut run)) = view_run(&physical, at, len - k) else { - return false; - }; - while k + run < len { - let Some(next_at) = from.checked_add(k + run) else { - break; - }; - let Some((next, extra)) = view_run(&physical, next_at, len - k - run) else { - break; - }; - if Arc::ptr_eq(&next.section, &first.section) && next.index == first.index + run / PAGE - { - run += extra; - } else { - break; - } - } - if !map(&mut physical, to + k, run, first) { + if !map(&mut physical, to + k, PAGE, slice) { return false; } - k += run; } true } -fn coalesce_placeholders(base: usize, len: usize) { - let Some(target_end) = base.checked_add(len) else { - return; - }; - let size = size_of::(); - // SAFETY: a pseudo handle needs no closing. - let process = unsafe { GetCurrentProcess() }; - let query = |at: usize| -> Option { - // SAFETY: plain data; zero is valid before VirtualQueryEx fills it. - let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - // SAFETY: `info` has room for `size` bytes. - let n = unsafe { VirtualQueryEx(process, at as *const c_void, &mut info, size) }; - (n != 0).then_some(info) - }; - let Some(first) = query(base) else { - return; - }; - if first.State != MEM_RESERVE { - return; - } - let start = first.AllocationBase as usize; - let mut end = first.BaseAddress as usize + first.RegionSize; - if end >= target_end { - return; - } - while end < target_end { - let Some(next) = query(end) else { - return; - }; - if next.State != MEM_RESERVE || next.RegionSize == 0 { - return; - } - let next_end = next.BaseAddress as usize + next.RegionSize; - if next_end <= end { - return; - } - end = next_end; - } - // SAFETY: `[start, end)` is the exact span of adjacent placeholders to merge. - unsafe { - VirtualFree( - start as *mut c_void, - end - start, - MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS, - ); - } -} - /// Maps `slice` and the slices after it over `[base, base + len)`, which /// must lie in one placeholder. fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { - coalesce_placeholders(base, len); // SAFETY: splits the placeholder around the range (failing harmlessly // when the range is the whole placeholder), then maps the section // there; both act only on placeholders. @@ -866,9 +744,8 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { } // New contents, read-write: the GPU side's copies no longer guard it. victory_gpu::title_memory_remapped(base, len); - static LOOKUP: std::sync::Once = std::sync::Once::new(); - LOOKUP.call_once(|| victory_gpu::set_alias_lookup(other_views)); - note_aliases(base, len, &slice, true); + // What the range shows now, for the GPU side's in-place census. + victory_gpu::title_memory_view(base, len, slice.section.0 as usize, (slice.index * PAGE) as u64); physical.views.insert(base, (len, slice)); true } @@ -931,7 +808,8 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { return; } let end = base + len; - // Views do not overlap: the one holding `base`, then those starting inside. + // Views do not overlap: the one holding `base`, then those starting + // inside (the GPU's page mappings make one view per page). let first = physical .views .range(..=base) @@ -947,7 +825,6 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { continue; }; victory_gpu::title_memory_remapped(at, size); - note_aliases(at, size, &slice, false); // SAFETY: a view we mapped; it becomes a placeholder again. unsafe { UnmapViewOfFile2( @@ -1009,6 +886,25 @@ pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut Workin gpu_optimal_limit: gpu_optimal, ..Default::default() }; + // What the title is told, logged at the first asking and at every + // 1,024th: "used" is all the process has committed, the layer's own + // memory and the card's included (27 GB in run 60's gameplay against a + // limit of 13.5 GB). A title that budgets its streaming from these two + // figures believes it is far over its limit. + // shortcut: the figure is not yet the title's own memory alone (its + // heaps and the pages it mapped); count those if this line shows the + // title asking. + static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let asked = ASKED.fetch_add(1, Ordering::Relaxed); + if asked.is_multiple_of(1024) { + tracing::info!( + asked = asked + 1, + which = _which, + limit_mb = stats.title_limit >> 20, + used_mb = stats.title_used >> 20, + "the title asks how much memory it uses" + ); + } // SAFETY: checked non-null; the title passes room for the structure. unsafe { out.write(stats) }; 1 @@ -1253,69 +1149,55 @@ mod tests { assert_eq!(XMemIsToolsMemAvailable(), 0); } + /// A thread that reads a mapped page in place, as the GPU side reads a + /// texture, never meets the moment in which the runtime has taken the + /// page's view away to map it again: mapping the same pages at the same + /// address unmaps the view and maps a new one, and without the lock the + /// reader faults on a page "reserved, never committed" (the crashes of + /// runs 71 and 74). #[test] - fn remapping_split_placeholders_and_coalesced_aliases() { - let (a_pages, b_pages) = (allocate(3), allocate(1)); - let reserve = |pages: usize| { - let p = XMemVirtualAlloc( - std::ptr::null_mut(), - pages * PAGE, - MEM_RESERVE | PAGES_64K, - 0, - PAGE_READWRITE, - ); - assert!(!p.is_null()); - p - }; - let at = |p: *mut c_void, page: usize| p.wrapping_byte_add(page * PAGE); - let (src, dst) = (reserve(4), reserve(4)); - - assert_eq!(XMemMapPhysicalPages(src, 3, a_pages.as_ptr()), src); - assert_eq!( - XMemMapPhysicalPages(at(src, 1), 1, std::ptr::null()), - at(src, 1) - ); - assert_eq!(XMemMapPhysicalPages(src, 3, a_pages.as_ptr()), src); - assert_eq!( - physical().views.get(&(src as usize)).map(|v| v.0), - Some(3 * PAGE) - ); - assert_eq!( - XMemMapPhysicalPages(at(src, 3), 1, b_pages.as_ptr()), - at(src, 3) - ); - - // SAFETY: all four pages of `src` are mapped read-write. - unsafe { - for i in 0..4 { - at(src, i).cast::().write((i + 10) as u8); - } - } - - assert_eq!( - XMemMapPhysicalPages(at(dst, 1), 1, a_pages.as_ptr()), - at(dst, 1) - ); - assert!(map_alias(dst as u64, src as u64, 4 * PAGE as u64)); - assert_eq!( - physical().views.get(&(dst as usize)).map(|v| v.0), - Some(3 * PAGE) - ); - assert_eq!( - physical().views.get(&(at(dst, 3) as usize)).map(|v| v.0), - Some(PAGE) + fn a_read_in_place_never_meets_the_gap_of_a_remapping() { + use std::sync::atomic::{AtomicBool, Ordering}; + let mut pages = [0usize; 3]; + let mut n = 3; + assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + let a = XMemVirtualAlloc( + std::ptr::null_mut(), + 3 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, ); - // SAFETY: all four aliased pages of `dst` are mapped read-write. - unsafe { - for i in 0..4 { - assert_eq!(at(dst, i).cast::().read(), (i + 10) as u8); - } + assert!(!a.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + // SAFETY: mapped read-write. + unsafe { a.cast::().write(1) }; + let first = a as usize; + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let reader = { + let stop = stop.clone(); + std::thread::spawn(move || { + let mut reads = 0u64; + while !stop.load(Ordering::Relaxed) { + let _reading = victory_gpu::title_memory_reading(); + // SAFETY: the page is mapped whenever no change of + // mapping is under way, and none is while `_reading` + // is held. + assert_eq!(unsafe { (first as *const u8).read_volatile() }, 1); + reads += 1; + } + reads + }) + }; + for _ in 0..2000 { + // The same pages at the same address: the view goes and comes + // back, with the same bytes. + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); } - - assert!(map_alias(dst as u64, 0, 4 * PAGE as u64)); - assert_eq!(XMemMapPhysicalPages(src, 4, std::ptr::null()), src); - assert_eq!(XMemFreePhysicalPages(3, a_pages.as_ptr()), 1); - assert_eq!(XMemFreePhysicalPages(1, b_pages.as_ptr()), 1); + stop.store(true, Ordering::Relaxed); + assert!(reader.join().expect("the reader never faulted") > 0); + assert_eq!(XMemMapPhysicalPages(a, 3, std::ptr::null()), a); + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); } #[test] diff --git a/crates/victory-hle/src/modules/xnetworking.rs b/crates/victory-hle/src/modules/xnetworking.rs index 8670ff2..c0b21a3 100644 --- a/crates/victory-hle/src/modules/xnetworking.rs +++ b/crates/victory-hle/src/modules/xnetworking.rs @@ -18,7 +18,7 @@ pub const PROVIDER: Guid = Guid::new( [0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a], ); -/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x18-0x88) +/// As the title (2026) asks for it; the slots it calls (0x18-0x88) /// take the same arguments as under the provider's own id (older titles). pub const IID_2026: Guid = Guid::new( 0xbf23_46b2, diff --git a/crates/victory-hle/src/modules/xpackage.rs b/crates/victory-hle/src/modules/xpackage.rs index 4f03635..315faac 100644 --- a/crates/victory-hle/src/modules/xpackage.rs +++ b/crates/victory-hle/src/modules/xpackage.rs @@ -20,7 +20,7 @@ pub const PROVIDER: Guid = Guid::new( [0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e], ); -/// As Grand Theft Auto VI (2026) asks for it. Its slots up to 0xd0 take the +/// As the title (2026) asks for it. Its slots up to 0xd0 take the /// arguments the public API lists in the same order; 0x110 uninstalls a /// package, 0x128/0x130 mount one with UI, 0x138 enumerates packages. pub const IID_2026: Guid = Guid::new( @@ -139,7 +139,7 @@ extern "system" fn register_progress( /// 0: ready. // shortcut: every selector counts as installed, including ones the // package's layout does not have (the console answers those with an -// invalid-selector error); Grand Theft Auto VI asks only about its own +// invalid-selector error); the title asks only about its own // chunks, which a full install has. extern "system" fn find_availability( _: This, @@ -210,7 +210,7 @@ extern "system" fn estimate_download( } // shortcut: accepted but nothing is removed (the package folder is the -// user's), so the chunks stay ready; Grand Theft Auto VI's one call site +// user's), so the chunks stay ready; the title's one call site // (title+0x293b4b0, its chunk manager) would then see them still installed. extern "system" fn uninstall_chunks( _: This, @@ -256,7 +256,7 @@ extern "system" fn mount_result( /// Titles enumerate content packages (kind 1); there are none. // shortcut: the game kind (0) also lists nothing, not this installation; -// Grand Theft Auto VI enumerates only content (kind 1, title+0x2937bf0). +// The title enumerates only content (kind 1, title+0x2937bf0). extern "system" fn enumerate( _: This, kind: u32, diff --git a/crates/victory-hle/src/modules/xstore.rs b/crates/victory-hle/src/modules/xstore.rs index 3e29422..9e2b74b 100644 --- a/crates/victory-hle/src/modules/xstore.rs +++ b/crates/victory-hle/src/modules/xstore.rs @@ -20,7 +20,7 @@ pub const PROVIDER: Guid = Guid::new( 0x448c, [0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c], ); -/// As Grand Theft Auto VI (2026) asks for it; every slot it calls takes +/// As the title (2026) asks for it; every slot it calls takes /// the public API's arguments in the 2020 order. pub const IID_2026: Guid = Guid::new( 0xb09d_803c, diff --git a/crates/victory-hle/src/modules/xsystem.rs b/crates/victory-hle/src/modules/xsystem.rs index a3a1d62..bf091eb 100644 --- a/crates/victory-hle/src/modules/xsystem.rs +++ b/crates/victory-hle/src/modules/xsystem.rs @@ -41,7 +41,7 @@ const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE="; pub static OBJECT: Object = Object::new("system", &VTABLE); pub static ANALYTICS_OBJECT: Object = Object::new("analytics", &ANALYTICS_VTABLE); -/// The interface as Grand Theft Auto VI (2026) asks for it; it calls the +/// The interface as the title (2026) asks for it; it calls the /// same three slots (0x18, 0x20, 0x28) with the same arguments. pub const IID_2026: Guid = Guid::new( 0x1861_cf2e, diff --git a/crates/victory-hle/src/modules/xuser.rs b/crates/victory-hle/src/modules/xuser.rs index 8b48dfc..6019381 100644 --- a/crates/victory-hle/src/modules/xuser.rs +++ b/crates/victory-hle/src/modules/xuser.rs @@ -81,7 +81,7 @@ pub static DEVICE_OBJECT: Object = Object::new("user devices", &DEVICE_VTABLE); pub const INTERFACES: &[Interface] = &[ (PROVIDER, IID, &OBJECT), - // Grand Theft Auto VI (2026) asks with the provider's id; its thunks call + // The title (2026) asks with the provider's id; its thunks call // the same slots with the same arguments (0x108/0x110 change events). (PROVIDER, PROVIDER, &OBJECT), (PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT), diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index d4bb8ec..cc13821 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -26,40 +26,12 @@ static IMAGE_PATHS: Mutex> = Mutex::new(Vec::new()); /// own path (`GetModuleFileName`) to find its data, and must not get our /// cache copy. pub fn set_image_path(base: usize, path: &Path) { - let path = absolute_title_path(path); + let path = std::path::absolute(path).unwrap_or_else(|_| path.to_owned()); let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); paths.retain(|(b, _)| *b != base); paths.push((base, path)); } -/// Makes `path` absolute, as the title stored it: an already-absolute path -/// is kept as is; a relative path is made absolute against the current -/// directory. A Windows path is absolute everywhere, regardless of the -/// host: `C:\title\game.exe` is a title path, not a bare relative one -/// that the host would make absolute against the wrong root. -fn absolute_title_path(path: &Path) -> PathBuf { - if path.is_absolute() || title_absolute(path) { - return path.to_path_buf(); - } - std::path::absolute(path).unwrap_or_else(|_| path.to_owned()) -} - -/// Whether `path` looks like an absolute Windows path: a drive root (`C:\`), -/// a drive-rooted path (`C:\title\game.exe`) or a UNC path (`\\server\share`). -fn title_absolute(path: &Path) -> bool { - let s = path.to_string_lossy(); - let bytes = s.as_bytes(); - // A drive root: `X:` (nothing else), then a separator. - if bytes.len() >= 2 - && bytes[0].is_ascii_alphabetic() - && bytes[1] == b':' - && (bytes.len() == 2 || bytes[2] == b'\\' || bytes[2] == b'/') - { - return true; - } - s.starts_with("\\\\") -} - /// Forgets a title image that was unmapped again. pub fn forget_image(base: usize) { let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); @@ -79,19 +51,10 @@ pub fn image_named(file: &str) -> Option { let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); paths .iter() - .find(|(_, p)| title_file_name(p).is_some_and(|n| n.eq_ignore_ascii_case(file))) + .find(|(_, p)| p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(file))) .map(|(b, _)| *b) } -/// The file name of a path, whatever its shape: `C:\title\Mapped.dll` and -/// `C:\title/Mapped.dll` both name `Mapped.dll`, on whatever host the title -/// runs on. -fn title_file_name(path: &Path) -> Option { - let s = path.to_string_lossy(); - let name = s.rsplit(['\\', '/']).next()?; - Some(name.to_string()) -} - /// Maps a title DLL the title loads itself (`LoadLibrary`) and returns its /// base; `Ok(None)` if `file` is not one of the title's DLLs. pub type TitleDllLoader = Box Result, String> + Send + Sync>; @@ -185,22 +148,10 @@ fn elements(text: &str) -> Vec<(String, String)> { .next() .unwrap_or(""); path.push(name); - // Text up to the first child belongs to this element. A self-closing - // element has none, so whatever follows it belongs to its parent. - let body = if closed { - String::new() - } else { - let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); - [ - ("<", "<"), - (">", ">"), - (""", "\""), - ("'", "'"), - ("&", "&"), - ] + let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); + let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")] .iter() - .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)) - }; + .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); out.push((path.join("/"), body)); if closed { path.pop(); @@ -225,7 +176,7 @@ pub fn title() -> Title { } /// Gives the process the console's millisecond timers. Titles pace -/// themselves with short waits (Grand Theft Auto VI's audio mixer sleeps +/// themselves with short waits (the title's audio mixer sleeps /// about 4 ms per 5.3 ms block) and cannot tune the timer on the console; /// a desktop process waits in 15.6 ms ticks unless it asks for finer ones, /// and Windows 11 drops that request while the window is hidden unless the @@ -259,14 +210,6 @@ pub fn use_console_timers() { mod tests { use super::*; - /// The body recorded for `path`, if any element has it. - fn body<'a>(elements: &'a [(String, String)], path: &str) -> Option<&'a str> { - elements - .iter() - .find(|(p, _)| p == path) - .map(|(_, text)| text.as_str()) - } - #[test] fn reads_title_id_store_id_and_storage_quota() { let text = "\u{feff}\n\ @@ -280,139 +223,4 @@ mod tests { assert_eq!(t.store_id, "9&C"); assert_eq!(Title::from_manifest("").storage_bytes, 0); } - - #[test] - fn elements_record_the_path_of_each_nested_element() { - let found = elements("x"); - for (path, text) in [("A", ""), ("A/B", ""), ("A/B/C", "x")] { - assert_eq!(body(&found, path), Some(text), "{path}"); - } - assert_eq!(found.len(), 3, "one entry per element"); - } - - #[test] - fn a_self_closing_element_owns_no_text() { - // The words after `/>` belong to the parent, not to `Flag`. - let found = elements("owned by the parentok"); - assert_eq!(body(&found, "Game/Flag"), Some("")); - assert_eq!(body(&found, "Game/Name"), Some("ok")); - // Neighbours with nothing between them are still empty. - let neighbours = elements(""); - assert_eq!(body(&neighbours, "R/A"), Some("")); - assert_eq!(body(&neighbours, "R/B"), Some("")); - } - - #[test] - fn comments_cdata_and_declarations_are_skipped() { - let found = - elements("d]]>1"); - assert_eq!(body(&found, "G/X"), None, "inside a comment"); - assert_eq!(body(&found, "G/Y"), None, "inside CDATA"); - assert_eq!(body(&found, "G/Z"), Some("1")); - } - - #[test] - fn predefined_entities_are_decoded_once() { - assert_eq!( - body(&elements("<>&"'"), "A"), - Some("<>&\"'") - ); - // One pass: `&lt;` is the text `<`, not a second `<`. - assert_eq!(body(&elements("&lt;"), "A"), Some("<")); - } - - #[test] - fn unterminated_markup_is_ignored_without_panicking() { - let found = elements("x"); - assert!(elements("<").is_empty()); - } - - #[test] - fn missing_manifest_yields_defaults() { - for text in [ - "", - "", - "1", - ] { - let title = Title::from_manifest(text); - assert_eq!( - (title.id, title.store_id.as_str(), title.storage_bytes), - (0, "", 0), - "{text:?}" - ); - assert_eq!(title.storage, PathBuf::new(), "{text:?}"); - } - } - - #[test] - fn lowercase_hex_id_and_quota_in_bytes() { - let title = Title::from_manifest( - "deadbeef\ - 2", - ); - assert_eq!(title.id, 0xDEAD_BEEF); - assert_eq!(title.storage_bytes, 2 << 20); - } - - #[test] - fn invalid_id_and_missing_quota_are_zero() { - let title = Title::from_manifest("0x12"); - assert_eq!((title.id, title.storage_bytes), (0, 0)); - } - - #[test] - fn store_id_is_trimmed_and_entity_decoded() { - let title = Title::from_manifest(" a&b "); - assert_eq!(title.store_id, "a&b"); - } - - #[test] - fn commented_and_cdata_ids_are_ignored() { - let title = Title::from_manifest( - "x]]>\ - 2", - ); - assert_eq!(title.id, 2); - assert_eq!(title.store_id, ""); - } - - #[test] - fn the_first_element_at_a_path_wins() { - let title = Title::from_manifest("12"); - assert_eq!(title.id, 1); - } - - #[test] - fn saves_live_beside_storage() { - assert_eq!(Title::default().saves(), PathBuf::from("saves")); - let title = Title { - storage: PathBuf::from("data/0000/storage"), - ..Title::default() - }; - assert_eq!(title.saves(), PathBuf::from("data/0000/saves")); - } - - #[test] - fn image_registry_remembers_replaces_and_forgets() { - let base = 0x7DFF_5A5A_0001; - let first = Path::new(r"C:\victory-test\victory-runtime-image.dll"); - let second = Path::new(r"D:\victory-test\victory-renamed-image.dll"); - let name = |path: &Path| path.file_name().unwrap().to_owned(); - - set_image_path(base, first); - assert_eq!(image_path(base).map(|p| name(&p)), Some(name(first))); - assert_eq!(image_named("VICTORY-RUNTIME-IMAGE.DLL"), Some(base)); - - // A second file at the same base replaces the first. - set_image_path(base, second); - assert_eq!(image_path(base).map(|p| name(&p)), Some(name(second))); - assert_eq!(image_named("victory-runtime-image.dll"), None); - assert_eq!(image_named("victory-renamed-image.dll"), Some(base)); - - forget_image(base); - assert_eq!(image_path(base), None); - assert_eq!(image_named("victory-renamed-image.dll"), None); - } } diff --git a/crates/victory-loader/Cargo.toml b/crates/victory-loader/Cargo.toml index 4b0e098..0f3497b 100644 --- a/crates/victory-loader/Cargo.toml +++ b/crates/victory-loader/Cargo.toml @@ -14,7 +14,6 @@ anyhow.workspace = true thiserror.workspace = true tracing.workspace = true blake3.workspace = true -hex = "0.4" [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = [ @@ -25,6 +24,7 @@ windows-sys = { workspace = true, features = [ "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", + "Win32_System_Performance", "Win32_System_Threading", ] } diff --git a/crates/victory-loader/src/console_insn.rs b/crates/victory-loader/src/console_insn.rs new file mode 100644 index 0000000..ca1eb8c --- /dev/null +++ b/crates/victory-loader/src/console_insn.rs @@ -0,0 +1,249 @@ +//! Instructions the console's CPU (Zen 2) has and an Intel PC's lacks, emulated: the title's +//! code raises STATUS_ILLEGAL_INSTRUCTION on them (the title zeroes memory with a `clzero` loop at +//! its first frames), and the vectored handler steps over them here. +//! +//! Ported from XCL (github.com/ivall/xcl, GPL-2.0-only): `insn.rs` (decoder, as +//! `console_insn_decode.rs`, unchanged) and `eh.rs` `emulate_console_only`. + +#[path = "console_insn_decode.rs"] +mod decode; + +use decode::ConsoleOnly; +use std::cell::Cell; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT; + +const CONTINUE_EXECUTION: i32 = -1; + +/// Whether what Windows said about memory is remembered per thread (the regions it found +/// writable, the code bytes it found readable) and not asked again at every emulated +/// instruction. A query walks the pages of the region it answers for: asked from outside, it +/// took 2-9 ms in the title's heaps of 0.6-2.2 GB and 89 ms in its 6.2 GB page pool (run 30), +/// and the title zeroes blocks of them with `clzero` loops all through a frame: six of its +/// threads spent 25-78 % of their time inside that query (runs 29 and 30), about 27 s of +/// processor time in Windows per 9 s frame. On by default; `VICTORY_CLZERO_ASK=1` asks every +/// time, as before. +fn remembers() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CLZERO_ASK").is_none_or(|v| v != "1")) +} + +/// Answers a remembered region gives before Windows is asked about it again: one freed or +/// protected meanwhile is forgotten then. +const ANSWERS: u32 = 4096; + +thread_local! { + /// The regions Windows last said are committed and writable (start, end), newest first, + /// and the answers they gave since they were emptied. + static WRITABLE: Cell<([(usize, usize); 4], u32)> = const { Cell::new(([(0, 0); 4], 0)) }; + /// Faulting addresses and the code bytes found readable there, newest first. + static CODE: Cell<[(usize, usize); 8]> = const { Cell::new([(0, 0); 8]) }; +} + +/// Instructions emulated, the times Windows was asked about memory for them, and the bytes +/// `clzero` loops zeroed, since the start. +static EMULATED: AtomicU64 = AtomicU64::new(0); +static ASKED: AtomicU64 = AtomicU64::new(0); +static ZEROED: AtomicU64 = AtomicU64::new(0); + +fn readable(va: usize, bytes: usize) -> bool { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery}; + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0; + ASKED.fetch_add(1, Relaxed); + found && m.State == MEM_COMMIT && m.Protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 && m.BaseAddress as usize + m.RegionSize >= va + bytes +} + +fn writable(va: usize, bytes: usize) -> bool { + writable_to(va, va + bytes) == Some(va + bytes) +} + +/// Where the committed, writable memory that `va` lies in ends, at most `end`; None if `va` +/// is not in such memory. A region found is remembered ([`remembers`]). +/// shortcut: a remembered region that was freed or protected since is written all the same +/// for up to [`ANSWERS`] answers: the write then faults inside the handler, which the guard +/// on view memory opens as it does any write, and which is a crash otherwise (as the +/// unchecked single-line emulation behind this one already is). +fn writable_to(va: usize, end: usize) -> Option { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, VirtualQuery}; + let remember = remembers(); + if remember { + let (regions, answers) = WRITABLE.with(Cell::get); + if let Some(&(_, to)) = regions.iter().find(|&&(from, to)| from <= va && va < to) { + let next = if answers >= ANSWERS { ([(0, 0); 4], 0) } else { (regions, answers + 1) }; + WRITABLE.with(|w| w.set(next)); + return Some(to.min(end)); + } + } + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0; + ASKED.fetch_add(1, Relaxed); + if !found || m.State != MEM_COMMIT || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 { + return None; + } + let (from, to) = (m.BaseAddress as usize, m.BaseAddress as usize + m.RegionSize); + if remember { + WRITABLE.with(|w| { + let (mut regions, answers) = w.get(); + regions.rotate_right(1); + regions[0] = (from, to); + w.set((regions, answers)); + }); + } + Some(to.min(end)) +} + +/// An illegal instruction at `ctx.Rip`: a console-only one is emulated and stepped over +/// (`CONTINUE_EXECUTION`); anything else returns 0 (the crash report and the title's handlers +/// see it). +/// +/// # Safety +/// `ctx` is the faulting thread's context, from the exception being dispatched. +pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { + let rip = ctx.Rip as usize; + // The same few instructions fault again and again: their bytes are asked about once. + let known = if remembers() { CODE.with(Cell::get) } else { [(0, 0); 8] }; + let n = match known.iter().find(|&&(at, n)| at == rip && n > 0) { + Some(&(_, n)) => n, + None => { + if !readable(rip, 1) { + return 0; + } + let n = (1..=16).rev().find(|&n| readable(rip, n)).unwrap_or(0); + if remembers() { + let mut known = known; + known.rotate_right(1); + known[0] = (rip, n); + CODE.with(|c| c.set(known)); + } + n + } + }; + // SAFETY: `n` bytes at `rip` are readable. + let code = unsafe { std::slice::from_raw_parts(rip as *const u8, n) }; + let Some((what, len)) = decode::decode(code) else { return 0 }; + static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + if let Ok(mut seen) = SEEN.lock() + && !seen.contains(&std::mem::discriminant(&what)) + { + seen.push(std::mem::discriminant(&what)); + if what != ConsoleOnly::Ud2 { + tracing::warn!(instruction = ?what, at = format_args!("{rip:#x}"), "a console CPU instruction this CPU lacks: emulated (logged once)"); + } + } + match what { + ConsoleOnly::Ud2 => return 0, + ConsoleOnly::Clwb => { + // nothing to write back on the PC: patched to NOPs, no exception next time + use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect}; + let mut old = 0u32; + // SAFETY: the instruction's own bytes, made writable for the patch and restored. + unsafe { + if VirtualProtect(rip as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 { + std::slice::from_raw_parts_mut(rip as *mut u8, len).fill(0x90); + VirtualProtect(rip as *const _, len, old, &mut old); + } + } + } + ConsoleOnly::Monitorx => {} + ConsoleOnly::Mwaitx => std::hint::spin_loop(), + ConsoleOnly::Clzero => { + // with an address-size prefix (0x67) the line is at EAX, zero-extended + let a32 = code[..len - 3].contains(&0x67); + let line = (if a32 { ctx.Rax & 0xFFFF_FFFF } else { ctx.Rax } as usize) & !63; + if !writable(line, 64) { + return 0; // the real instruction faults there too + } + // SAFETY: the 64-byte line is committed and writable. + unsafe { std::ptr::write_bytes(line as *mut u8, 0, 64) }; + } + ConsoleOnly::ClzeroLoop { end_reg } => { + // the whole `clzero; add rax,40h; cmp rax,end; jb` loop at once + let regs: [u64; 16] = [ + ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15, + ]; + let end = regs[end_reg as usize & 15] as usize; + let start = ctx.Rax as usize; + if end > start && end - start < 2 << 30 { + // Region by region: a block may lie across several (the title's pages are + // mapped one view each), and one answer for all of it was a refusal, after + // which every 64-byte line took an exception of its own. + let mut at = start; + while at < end { + let Some(to) = writable_to(at, end) else { break }; + // SAFETY: committed and writable from `at` to `to`. + unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) }; + at = to; + } + if at == start { + return 0; + } + ZEROED.fetch_add((at - start) as u64, Relaxed); + if at < end { + // What follows is not writable: the loop goes on there (the same + // instruction again), where the real one faults too. + ctx.Rax = at as u64; + return CONTINUE_EXECUTION; + } + } + ctx.Rax = end as u64; + } + ConsoleOnly::Rdpru => { + let mut v = 0i64; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut v) }; + let v = if ctx.Rcx as u32 <= 1 { v as u64 } else { 0 }; + ctx.Rax = v & 0xFFFF_FFFF; + ctx.Rdx = v >> 32; + } + ConsoleOnly::Rdpid(r) => { + // SAFETY: no preconditions. + let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as u64; + let regs: [&mut u64; 16] = [ + &mut ctx.Rax, &mut ctx.Rcx, &mut ctx.Rdx, &mut ctx.Rbx, &mut ctx.Rsp, &mut ctx.Rbp, &mut ctx.Rsi, &mut ctx.Rdi, &mut ctx.R8, &mut ctx.R9, &mut ctx.R10, &mut ctx.R11, &mut ctx.R12, &mut ctx.R13, + &mut ctx.R14, &mut ctx.R15, + ]; + *regs[r as usize & 15] = cpu; + } + // the low quadword changes; the high one is zeroed, as a Zen 5 does + ConsoleOnly::Extrq { dst, src, len, idx } => { + // SAFETY: the context's XMM registers (CONTEXT_FLOATING_POINT is captured for exceptions). + let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters }; + let (len, idx) = match src { + Some(s) => { + let c = x[s as usize & 15].Low; + (c as u8, (c >> 8) as u8) + } + None => (len, idx), + }; + let d = &mut x[dst as usize & 15]; + d.Low = decode::extrq(d.Low, len, idx); + d.High = 0; + } + ConsoleOnly::Insertq { dst, src, reg, len, idx } => { + // SAFETY: as above. + let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters }; + let s = x[src as usize & 15]; + let (len, idx) = if reg { (s.High as u8, (s.High >> 8) as u8) } else { (len, idx) }; + let d = &mut x[dst as usize & 15]; + d.Low = decode::insertq(d.Low, s.Low, len, idx); + d.High = 0; + } + } + ctx.Rip += len as u64; + // How often this runs at all (each one is an exception: a trip into Windows and back). + let emulated = EMULATED.fetch_add(1, Relaxed) + 1; + if emulated >= 1 << 16 && emulated.is_power_of_two() { + tracing::info!( + emulated, + asked = ASKED.load(Relaxed), + zeroed_mb = ZEROED.load(Relaxed) >> 20, + "console CPU instructions emulated so far, the times Windows was asked about memory for them, and what clzero loops zeroed" + ); + } + CONTINUE_EXECUTION +} diff --git a/crates/victory-loader/src/console_insn_decode.rs b/crates/victory-loader/src/console_insn_decode.rs new file mode 100644 index 0000000..08142f8 --- /dev/null +++ b/crates/victory-loader/src/console_insn_decode.rs @@ -0,0 +1,233 @@ +//! Instructions the console's CPU (Zen 2) has and a PC's may lack – a title raises +//! STATUS_ILLEGAL_INSTRUCTION on them on an Intel CPU before Ice Lake / Alder Lake (CLWB, +//! SHA) or on any Intel CPU (CLZERO, RDPRU, MONITORX / MWAITX and SSE4a's EXTRQ / INSERTQ, +//! which are AMD's). The exception handler (`eh`) emulates the ones decoded here and steps over +//! them. + +/// A console-only instruction at the faulting address. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConsoleOnly { + /// `clwb m8`: write a cache line back – nothing to do, the PC's memory is coherent + Clwb, + /// `clzero`: zero the 64-byte cache line at rAX + Clzero, + /// `clzero` loop: `clzero; add rax, 0x40; cmp rax, ; jb -12` – zero `[rax..reg)` + ClzeroLoop { end_reg: u8 }, + /// `rdpru`: ecx = 0 MPERF / 1 APERF → edx:eax (a counter) + Rdpru, + /// `monitorx` / `mwaitx`: a wait the emulation skips + Monitorx, + Mwaitx, + /// `rdpid r64`: TSC_AUX (the processor number) into the register (CONTEXT order: rax, rcx, + /// rdx, rbx, rsp, rbp, rsi, rdi, r8..r15) + Rdpid(u8), + /// SSE4a `extrq xmm, imm8 (length), imm8 (index)` / `extrq xmm1, xmm2` (`src` Some: the + /// length and index in xmm2's bits 5:0 and 13:8): a bit field of the low quadword, moved + /// down and zero-extended (the high quadword zeroed). Registers are XMM numbers 0..15. + Extrq { dst: u8, src: Option, len: u8, idx: u8 }, + /// SSE4a `insertq xmm1, xmm2, imm8 (length), imm8 (index)` / `insertq xmm1, xmm2` (`reg`: + /// the length and index in xmm2's bits 69:64 and 77:72): the low bits of xmm2 put into a + /// bit field of xmm1's low quadword. + Insertq { dst: u8, src: u8, reg: bool, len: u8, idx: u8 }, + /// `ud2`: the title's own trap (not emulated) + Ud2, +} + +/// A field length of SSE4a's six bits: 0 is 64. +fn field_len(len: u8) -> u32 { + match len & 63 { + 0 => 64, + n => n as u32, + } +} + +/// EXTRQ on a low quadword: `len` bits from bit `idx`, zero-extended (a field past bit 63 is +/// undefined on the console; here it is what a shift gives). +pub fn extrq(v: u64, len: u8, idx: u8) -> u64 { + let (len, idx) = (field_len(len), (idx & 63) as u32); + let field = v.checked_shr(idx).unwrap_or(0); + if len >= 64 { + field + } else { + field & ((1u64 << len) - 1) + } +} + +/// INSERTQ on a low quadword: the low `len` bits of `src` put at bit `idx` of `dst`. +pub fn insertq(dst: u64, src: u64, len: u8, idx: u8) -> u64 { + let (len, idx) = (field_len(len), (idx & 63) as u32); + let ones = if len >= 64 { u64::MAX } else { (1u64 << len) - 1 }; + let mask = ones.checked_shl(idx).unwrap_or(0); + (dst & !mask) | ((src & ones).checked_shl(idx).unwrap_or(0) & mask) +} + +/// The length of a ModRM-encoded operand (ModRM, SIB and displacement) at `b[0]`, None when the +/// bytes run out. +fn modrm_len(b: &[u8]) -> Option { + let modrm = *b.first()?; + let (md, rm) = (modrm >> 6, modrm & 7); + if md == 3 { + return Some(1); + } + let mut len = 1; + let mut base = rm; + if rm == 4 { + base = *b.get(1)? & 7; + len += 1; + } + len += match md { + 0 if base == 5 => 4, // disp32 (rip-relative, or a SIB without a base) + 0 => 0, + 1 => 1, + _ => 4, + }; + (b.len() >= len).then_some(len) +} + +/// The console-only instruction at the start of `code` and its length. +pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { + let mut i = 0; + // `rep`: the last of F2 / F3, which decides between them (and over 66) for SSE4a + let (mut p66, mut pf3, mut rep, mut rex) = (false, false, 0u8, 0u8); + while let Some(&b) = code.get(i) { + match b { + 0x66 => p66 = true, + 0xF2 => rep = 0xF2, + 0xF3 => { + pf3 = true; + rep = 0xF3; + } + 0x2E | 0x3E | 0x26 | 0x36 | 0x64 | 0x65 | 0x67 => {} + // REX counts only right before the opcode: one before a legacy prefix is ignored + 0x40..=0x4F => { + rex = b; + i += 1; + continue; + } + _ => break, + } + rex = 0; + i += 1; + } + if *code.get(i)? != 0x0F { + return None; + } + match (*code.get(i + 1)?, code.get(i + 2).copied()) { + (0x01, Some(0xFC)) => { + // clzero (0F 01 FC); add rax, 0x40 (48 83 C0 40); cmp rax, ([48|4C] 39 modrm); jb -12 (72 F4) + // (not after an 0x67: that CLZERO is at EAX, and the jb goes back to the 0F, past the + // prefix – it is stepped alone, the loop is taken from the next one) + if code.len() >= i + 12 + && !code[..i].contains(&0x67) + && code[i + 3..i + 7] == [0x48, 0x83, 0xC0, 0x40] + && (code[i + 7] == 0x48 || code[i + 7] == 0x4C) + && code[i + 8] == 0x39 + && code[i + 10..i + 12] == [0x72, 0xF4] + { + let rex_r = code[i + 7] == 0x4C; + let modrm = code[i + 9]; + let reg_idx = ((modrm >> 3) & 7) | if rex_r { 8 } else { 0 }; + Some((ConsoleOnly::ClzeroLoop { end_reg: reg_idx }, i + 12)) + } else { + Some((ConsoleOnly::Clzero, i + 3)) + } + } + (0x01, Some(0xFD)) => Some((ConsoleOnly::Rdpru, i + 3)), + (0x01, Some(0xFA)) => Some((ConsoleOnly::Monitorx, i + 3)), + (0x01, Some(0xFB)) => Some((ConsoleOnly::Mwaitx, i + 3)), + (0x0B, _) => Some((ConsoleOnly::Ud2, i + 2)), + // SSE4a: register operands only (ModRM mod 3); REX.R extends reg, REX.B rm + // (the last of F2 / F3 decides: F2 INSERTQ, F3 #UD; neither with 66: EXTRQ) + (0x78 | 0x79, Some(m)) if (rep == 0xF2 || (rep == 0 && p66)) && m >> 6 == 3 => { + let reg = ((m >> 3) & 7) | (rex & 4) << 1; + let rm = (m & 7) | (rex & 1) << 3; + let imm = |k: usize| code.get(i + 3 + k).copied(); + match (code[i + 1], rep == 0xF2) { + // extrq xmm(rm), imm8, imm8 – the ModRM reg field is /0 + (0x78, false) if (m >> 3) & 7 == 0 => Some((ConsoleOnly::Extrq { dst: rm, src: None, len: imm(0)?, idx: imm(1)? }, i + 5)), + (0x79, false) => Some((ConsoleOnly::Extrq { dst: reg, src: Some(rm), len: 0, idx: 0 }, i + 3)), + (0x78, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: false, len: imm(0)?, idx: imm(1)? }, i + 5)), + (0x79, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: true, len: 0, idx: 0 }, i + 3)), + _ => None, + } + } + // 66 0F AE /6 with a memory operand (without 66 it is xsaveopt) + (0xAE, Some(m)) if p66 && (m >> 3) & 7 == 6 && m >> 6 != 3 => Some((ConsoleOnly::Clwb, i + 2 + modrm_len(&code[i + 2..])?)), + // F3 0F C7 /7 with a register operand + (0xC7, Some(m)) if pf3 && (m >> 3) & 7 == 7 && m >> 6 == 3 => Some((ConsoleOnly::Rdpid((m & 7) | (rex & 1) << 3), i + 3)), + _ => None, + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + /// EXTRQ / INSERTQ as AMD's manual gives them: a length of 0 is 64. + #[test] + fn sse4a_bit_fields() { + assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 8, 16), 0xBC); + assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 0, 0), 0x1234_5678_9ABC_DEF0); + assert_eq!(extrq(0x8000_0000_0000_0000, 1, 63), 1); + assert_eq!(insertq(0xFFFF_FFFF_FFFF_FFFF, 0xAB, 8, 8), 0xFFFF_FFFF_FFFF_ABFF); + assert_eq!(insertq(0, 0x1FF, 4, 60), 0xF000_0000_0000_0000); + assert_eq!(insertq(0x1111, 0xDEAD_BEEF_0000_0000, 0, 0), 0xDEAD_BEEF_0000_0000); + for (v, len, idx) in [(0x0123_4567_89AB_CDEFu64, 12u8, 20u8), (u64::MAX, 63, 1), (0x55, 3, 0)] { + assert_eq!(extrq(insertq(0, v, len, idx), len, idx), extrq(v, len, 0)); + } + } + + #[test] + fn decodes_the_console_only_instructions() { + assert_eq!(decode(&[0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 3))); + // clzero loop against r10 (4C 39 D0 = cmp rax, r10) + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4]), + Some((ConsoleOnly::ClzeroLoop { end_reg: 10 }, 12)) + ); + // clzero loop against rdx (48 39 D0 = cmp rax, rdx) + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), + Some((ConsoleOnly::ClzeroLoop { end_reg: 2 }, 12)) + ); + // the same loop after an address-size prefix: that one CLZERO alone + assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 4))); + assert_eq!(decode(&[0x0F, 0x01, 0xFD]), Some((ConsoleOnly::Rdpru, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFA]), Some((ConsoleOnly::Monitorx, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFB]), Some((ConsoleOnly::Mwaitx, 3))); + assert_eq!(decode(&[0x0F, 0x0B]), Some((ConsoleOnly::Ud2, 2))); + // clwb [rax]; clwb [rcx+0x40]; clwb [rsp+8]; clwb [rip+disp32]; clwb [r8] + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 4))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x71, 0x40]), Some((ConsoleOnly::Clwb, 5))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24, 0x08]), Some((ConsoleOnly::Clwb, 6))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x35, 1, 2, 3, 4]), Some((ConsoleOnly::Clwb, 8))); + assert_eq!(decode(&[0x66, 0x41, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 5))); + // rdpid rax; rdpid r9 + assert_eq!(decode(&[0xF3, 0x0F, 0xC7, 0xF8]), Some((ConsoleOnly::Rdpid(0), 4))); + assert_eq!(decode(&[0xF3, 0x41, 0x0F, 0xC7, 0xF9]), Some((ConsoleOnly::Rdpid(9), 5))); + // not console-only: clflushopt (/7), xsaveopt (no 66), a plain mov, truncated bytes + // SSE4a, as a retail game has it (#216: insertq xmm0, xmm1 with length / index bytes) + assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x10]), Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 8, idx: 16 }, 6))); + assert_eq!(decode(&[0xF2, 0x45, 0x0F, 0x79, 0xC1]), Some((ConsoleOnly::Insertq { dst: 8, src: 9, reg: true, len: 0, idx: 0 }, 5))); + assert_eq!(decode(&[0x66, 0x0F, 0x78, 0xC2, 0x04, 0x08]), Some((ConsoleOnly::Extrq { dst: 2, src: None, len: 4, idx: 8 }, 6))); + assert_eq!(decode(&[0x66, 0x0F, 0x79, 0xCA]), Some((ConsoleOnly::Extrq { dst: 1, src: Some(2), len: 0, idx: 0 }, 4))); + assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08]), None, "an immediate missing"); + assert_eq!(decode(&[0x0F, 0x78, 0xC1, 0x08, 0x10]), None, "VMREAD without a prefix is not SSE4a"); + // prefixes as a Zen 5 runs them (Kalmarv on #209): the last of F2 / F3 decides, 66 next + // to them does not; 0x67 and a REX before a legacy prefix are ignored + let insertq = Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 16, idx: 16 }, 7)); + for code in [[0x66, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF2, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x67, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x41, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10]] { + assert_eq!(decode(&code), insertq, "{code:02x?}"); + } + for code in [[0xF2, 0xF3, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x66, 0xF3, 0x0F, 0x78, 0xC0, 0x10, 0x10]] { + assert_eq!(decode(&code), None, "#UD on the CPU: {code:02x?}"); + } + assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 4))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x38]), None); + assert_eq!(decode(&[0x0F, 0xAE, 0x30]), None); + assert_eq!(decode(&[0x48, 0x8B, 0x01]), None); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24]), None); + assert_eq!(decode(&[0x0F]), None); + } +} diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index ecd3ee5..3f77a88 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -64,11 +64,8 @@ pub fn log_crashes_to(file: std::path::PathBuf) { /// Appends a failure that is not an exception (the host GPU's) to the crash /// log, with the title's last debug output, and prints it. pub fn log_crash(text: &str) { - let text = format!( - "{text} -{}", - title_output() - ); + let text = format!("{text} +{}", title_output()); eprint!("{text}"); append_to_log(&text); } @@ -79,16 +76,9 @@ fn append_to_log(text: &str) { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs()); - let opened = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(file); + let opened = std::fs::OpenOptions::new().create(true).append(true).open(file); if let Ok(mut f) = opened { - let _ = write!( - f, - "unix time {now}, process {}\n{text}\n", - std::process::id() - ); + let _ = write!(f, "unix time {now}, process {}\n{text}\n", std::process::id()); } } @@ -115,9 +105,7 @@ fn title_output() -> String { let Ok(said) = SAID.try_lock() else { return String::new(); }; - said.iter() - .map(|l| format!(" title said: {l}\n")) - .collect() + said.iter().map(|l| format!(" title said: {l}\n")).collect() } /// Installs the handlers; call once before running title code. @@ -348,20 +336,12 @@ unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option { ((b(at + 3), b(at + 4)), at + 5) } else { // extrq reads its fields from src's low half, insertq from its high. - let f = if prefix == 0x66 { - xmm[src].Low - } else { - xmm[src].High as u64 - }; + let f = if prefix == 0x66 { xmm[src].Low } else { xmm[src].High as u64 }; ((f as u8, (f >> 8) as u8), at + 3) }; let (n, at_bit) = (u32::from(fields.0 & 63), u32::from(fields.1 & 63)); let bits = if n == 0 { 64 } else { n }; - let mask = if bits == 64 { - u64::MAX - } else { - (1u64 << bits) - 1 - }; + let mask = if bits == 64 { u64::MAX } else { (1u64 << bits) - 1 }; if prefix == 0x66 { // extrq: register form takes its fields from src, works on dst. if immediate && (modrm >> 3) & 7 != 0 { @@ -377,6 +357,15 @@ unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option { } unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + // an instruction of the console's CPU this one lacks: emulated, the title goes on + // SAFETY: the system passes valid exception pointers. + if unsafe { (*(*info).ExceptionRecord).ExceptionCode } == EXCEPTION_ILLEGAL_INSTRUCTION { + // SAFETY: the faulting thread's context, for the exception being dispatched. + let r = unsafe { crate::console_insn::emulate(&mut *(*info).ContextRecord) }; + if r != 0 { + return r; + } + } // SAFETY: the system passes valid exception pointers. if unsafe { emulate_amd_only(info) } { return -1; // EXCEPTION_CONTINUE_EXECUTION @@ -434,7 +423,8 @@ unsafe fn thrown(p: &[usize]) -> String { let types = p[3] + rva(p[2] + 12); let name = |i: usize| { let descriptor = p[3] + rva(p[3] + rva(types + 4 + 4 * i) + 4); - std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char).to_string_lossy() + std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char) + .to_string_lossy() }; let first = name(0); let value = match &*first { diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 3164cd9..b87d6c0 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -21,6 +21,8 @@ //! point on a thread with the stack size the image asks for; from then //! on, pass every thread start and end on to the attached images. +#[cfg(windows)] +mod console_insn; #[cfg(windows)] mod crash; pub mod prepare; @@ -36,12 +38,12 @@ mod tls; #[cfg(windows)] mod windows; -#[cfg(all(windows, feature = "diagnostics"))] -pub use crash::save_on_crash; #[cfg(windows)] pub use crash::{ locate, log_crash, log_crashes_to, note_title_output, report_crashes, report_unhandled, }; +#[cfg(all(windows, feature = "diagnostics"))] +pub use crash::save_on_crash; pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; #[cfg(all(windows, feature = "diagnostics"))] diff --git a/crates/victory-loader/src/prepare.rs b/crates/victory-loader/src/prepare.rs index cd5d574..c893508 100644 --- a/crates/victory-loader/src/prepare.rs +++ b/crates/victory-loader/src/prepare.rs @@ -1,7 +1,6 @@ //! Turns a title's image into something the Windows loader maps but does //! not run. Pure byte manipulation, so it is testable on any host. -use tracing; use victory_pe::layout::{self, dir, dll_flags, file_flags}; use victory_pe::{ImageInfo, PeError}; @@ -107,15 +106,6 @@ pub fn prepare(original: &[u8]) -> Result { } } - // Apply VICTORY_PATCH if set - if let Some(patch_env) = std::env::var_os("VICTORY_PATCH") { - let patch_env = patch_env.to_string_lossy().into_owned(); - let patches = parse_victory_patch(&patch_env); - if let Err(e) = apply_victory_patches(&mut bytes, &patches) { - tracing::warn!(target: "victory-loader", "VICTORY_PATCH application failed: {e}"); - } - } - Ok(PreparedImage { info, bytes, @@ -183,67 +173,11 @@ fn write(bytes: &mut [u8], at: usize, v: &[u8]) -> Result<(), PrepareError> { Ok(()) } -/// Simple hex decoder for VICTORY_PATCH bytes (no external `hex` crate needed). -/// Parses a VICTORY_PATCH environment variable value. -/// Format: `::` -/// Multiple patches can be specified by setting the env var multiple times -/// or using a separator (here we support space-separated multiple entries). -fn parse_victory_patch(env_val: &str) -> Vec<(String, u32, Vec)> { - let mut patches = Vec::new(); - for part in env_val.split_whitespace() { - let parts: Vec<&str> = part.split(':').collect(); - if parts.len() != 3 { - tracing::warn!(target: "victory-loader", "invalid VICTORY_PATCH format: {part}"); - continue; - } - let module = parts[0].to_string(); - let rva = u32::from_str_radix(parts[1], 16).unwrap_or(0); - let bytes = hex::decode(parts[2].trim()).unwrap_or_else(|_| Vec::new()); - patches.push((module, rva, bytes)); - } - patches -} - -/// Applies a list of VICTORY_PATCH entries to the image bytes. -/// Each patch is logged via `tracing::info!` with module, rva, old bytes, new bytes. -fn apply_victory_patches( - bytes: &mut [u8], - patches: &[(String, u32, Vec)], -) -> Result<(), PrepareError> { - for (module, rva, new_bytes) in patches { - // Verify the RVA is within the file bounds - if *rva as usize >= bytes.len() { - tracing::warn!(target: "victory-loader", "VICTORY_PATCH rva {:#x} outside file size {}", rva, bytes.len()); - continue; - } - // Save the old bytes for logging - let old_bytes = bytes[*rva as usize..*rva as usize + new_bytes.len()].to_vec(); - // Apply the patch - bytes[*rva as usize..*rva as usize + new_bytes.len()].copy_from_slice(new_bytes); - // Log the patch application - let old_hex = old_bytes - .iter() - .map(|b| format!("{:02x}", b)) - .collect::>() - .join(""); - let new_hex = new_bytes - .iter() - .map(|b| format!("{:02x}", b)) - .collect::>() - .join(""); - tracing::info!(target: "victory-loader", "VICTORY_PATCH: module={}, rva={:#x}, old_bytes=[{}], new_bytes=[{}]", module, rva, old_hex, new_hex); - } - Ok(()) -} - #[cfg(test)] mod tests { - #[cfg(windows)] use super::*; - #[cfg(windows)] #[test] - #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn patches_own_test_binary() { let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); let prepared = prepare(&original).unwrap(); @@ -270,9 +204,7 @@ mod tests { assert_eq!(prepared.bytes.len(), original.len()); } - #[cfg(windows)] #[test] - #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn keeps_iat_slots_when_import_size_excludes_the_terminator() { let mut original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); let info = ImageInfo::parse(&original).unwrap(); @@ -341,9 +273,7 @@ mod tests { ); } - #[cfg(windows)] #[test] - #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn file_name_is_stable_per_build() { let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); let a = prepare(&original).unwrap(); diff --git a/crates/victory-loader/src/stacks.rs b/crates/victory-loader/src/stacks.rs index 9ba72ed..1d30910 100644 --- a/crates/victory-loader/src/stacks.rs +++ b/crates/victory-loader/src/stacks.rs @@ -27,35 +27,21 @@ pub fn dump_stacks_on_schedule() { let Ok(list) = std::env::var("VICTORY_STACKS") else { return; }; - let times = delays(&list); - if times.is_empty() { - return; - } + let mut times: Vec = list + .split(',') + .filter_map(|t| t.trim().parse().ok()) + .collect(); + times.sort_by(f64::total_cmp); let start = std::time::Instant::now(); std::thread::spawn(move || { - for at in times { + for t in times { + let at = std::time::Duration::from_secs_f64(t.max(0.0)); std::thread::sleep(at.saturating_sub(start.elapsed())); dump_stacks(); } }); } -/// The delays `VICTORY_STACKS` lists, soonest first. Entries that are not a -/// finite number of seconds are dropped: no `Duration` holds them (a huge -/// value overflows it, and `inf` and `NaN` parse but have no length), and -/// taking one would panic the dumping thread instead of timing a dump. A -/// negative time means "now". -fn delays(list: &str) -> Vec { - let mut times: Vec = list - .split(',') - .filter_map(|t| t.trim().parse::().ok()) - .filter(|t| t.is_finite()) - .filter_map(|t| std::time::Duration::try_from_secs_f64(t.max(0.0)).ok()) - .collect(); - times.sort_unstable(); - times -} - /// `THREAD_BASIC_INFORMATION` (ntddk). #[repr(C)] struct BasicInfo { @@ -206,28 +192,6 @@ fn name_of(thread: HANDLE) -> String { mod tests { use super::*; - #[test] - fn the_schedule_keeps_only_delays_a_sleeper_can_wait() { - use std::time::Duration; - // Times are trimmed, bad entries dropped, the rest sorted soonest first. - assert_eq!( - delays("2, 0.5 ,1.5,abc,,0.5"), - [ - Duration::from_millis(500), - Duration::from_millis(500), - Duration::from_millis(1500), - Duration::from_secs(2), - ] - ); - // A negative time means "now". - assert_eq!(delays("-3,1"), [Duration::ZERO, Duration::from_secs(1)]); - // `f64` parses `inf` and `NaN`, and a huge value overflows - // `Duration`: each would panic `from_secs_f64`. - assert_eq!(delays("inf,-inf,NaN,1e300,1"), [Duration::from_secs(1)]); - assert!(delays("").is_empty()); - assert!(delays(" , ,").is_empty()); - } - #[test] fn another_threads_stack_unwinds_to_its_start() { let (tx, rx) = std::sync::mpsc::channel(); diff --git a/crates/victory-loader/src/threads.rs b/crates/victory-loader/src/threads.rs index a7a85d0..903aebd 100644 --- a/crates/victory-loader/src/threads.rs +++ b/crates/victory-loader/src/threads.rs @@ -164,8 +164,8 @@ fn end_other_threads(keep: &[u32]) { CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, }; use windows_sys::Win32::System::Threading::{ - GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_QUERY_INFORMATION, - THREAD_TERMINATE, TerminateThread, + GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_TERMINATE, TerminateThread, + THREAD_QUERY_INFORMATION, }; // SAFETY: plain queries of the calling process and thread. let (process, me) = unsafe { (GetCurrentProcessId(), GetCurrentThreadId()) }; @@ -323,10 +323,7 @@ impl OwnTls { /// title callbacks. fn started_by_rust() -> bool { // SAFETY: the calling thread's pseudo handle. - starts_in( - unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, - c"", - ) + starts_in(unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, c"") } /// Whether `thread`'s start routine lies in the module named `module` diff --git a/crates/victory-loader/src/tls.rs b/crates/victory-loader/src/tls.rs index 6a1d523..3f65dd2 100644 --- a/crates/victory-loader/src/tls.rs +++ b/crates/victory-loader/src/tls.rs @@ -23,9 +23,6 @@ const TLS64_ADDRESS_OF_INDEX: usize = 16; /// `mov r64, gs:[0x58]` is `65 REX 8B ModRM 25 58 00 00 00`. const LOAD_LEN: usize = 9; const THUNK_SIZE: usize = 32; -/// The loader hands out TLS indexes below 1088; the thunks' `disp32` also -/// could not hold `index * 8` anywhere near `u32::MAX`. -const MAX_INDEX: u32 = (1 << 28) - 1; /// Redirects the image's TLS-array loads if the OS gave it an index other /// than 0. Returns the number of loads patched. @@ -34,30 +31,17 @@ const MAX_INDEX: u32 = (1 << 28) - 1; /// `base` is the image `info` describes, mapped and not yet running. pub(crate) unsafe fn redirect(base: usize, info: &ImageInfo) -> Result { let Some(tls) = &info.tls else { return Ok(0) }; - // Header values are untrusted: the directory must hold the index field, - // and the field must name a `u32` inside the image, never elsewhere. - let size = info.size_of_image as usize; - let directory = tls.directory_rva as usize; - if directory + TLS64_ADDRESS_OF_INDEX + size_of::() > size { - bail!("TLS directory at {directory:#x} runs past the image"); - } // SAFETY: the TLS directory and the index it points to are in the image; // the OS relocated the pointer and wrote the index. - let index_at = - unsafe { ((base + directory + TLS64_ADDRESS_OF_INDEX) as *const usize).read() } as *mut u32; - let at = index_at as usize; - if at < base || at - base + size_of::() > size { - bail!("_tls_index at {at:#x} is outside the image"); - } - // SAFETY: as above; bounded above. + let index_at = unsafe { + ((base + tls.directory_rva as usize + TLS64_ADDRESS_OF_INDEX) as *const usize).read() + } as *mut u32; + // SAFETY: as above. let index = unsafe { index_at.read() }; if index == 0 { return Ok(0); } - if index > MAX_INDEX { - bail!("TLS index {index} is larger than any the loader assigns"); - } - let thunks = thunks(near(base, size)?, index)?; + let thunks = thunks(near(base, info.size_of_image as usize)?, index)?; let mut patched = 0; for section in info .sections @@ -66,11 +50,6 @@ pub(crate) unsafe fn redirect(base: usize, info: &ImageInfo) -> Result { { let start = base + section.rva as usize; let len = section.virtual_size as usize; - if len == 0 { - // An empty section has no code and no protection to change; - // `VirtualProtect` refuses a zero length. - continue; - } let mut old = 0; // SAFETY: the section is part of the mapped image. if unsafe { VirtualProtect(start as _, len, PAGE_EXECUTE_READWRITE, &mut old) } == 0 { @@ -103,7 +82,7 @@ fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize { let c = &code[i..i + LOAD_LEN]; let rex = c[1]; let reg = usize::from((c[3] >> 3) & 7) | if rex & 4 != 0 { 8 } else { 0 }; - // shortcut: a byte match, not a decode. In Grand Theft Auto VI all + // shortcut: a byte match, not a decode. In the title all // 53,246 hits are instruction starts and none is missed (checked // against a full disassembly); decode .text if a title shows one. if c[0] == 0x65 @@ -194,8 +173,6 @@ fn near(base: usize, size: usize) -> Result<*mut u8> { #[cfg(test)] mod tests { use super::*; - use victory_pe::{SectionInfo, TlsInfo}; - use windows_sys::Win32::System::Memory::{MEM_RELEASE, VirtualFree}; /// Reads the thread's TLS array pointer the way title code does. fn tls_array() -> usize { @@ -205,13 +182,6 @@ mod tests { array } - /// `mov r64, gs:[0x58]`, as compilers spell it for `reg`. - fn load(reg: u8) -> [u8; LOAD_LEN] { - let high = reg >> 3; - let low = (reg & 7) << 3; - [0x65, 0x48 | high << 2, 0x8B, low | 4, 0x25, 0x58, 0, 0, 0] - } - #[test] fn loads_become_calls_that_yield_the_title_slot() { let page = near(tls_array as *const () as usize, 0).unwrap(); @@ -246,347 +216,4 @@ mod tests { unsafe { VirtualProtect(page as _, 4096, PAGE_READWRITE, &mut old) }; } } - - #[test] - fn every_register_load_becomes_a_call_but_the_stack_pointer() { - const AT: usize = 0x1000; - const BLOCK: usize = 0x2000; - for reg in 0..16u8 { - let mut code = load(reg).to_vec(); - code.push(0xC3); - let patched = patch(&mut code, AT, BLOCK); - if reg == 4 { - // A `mov rsp, ...` thunk would move the stack out from under - // its own `ret`, so it is the one register left alone. - assert_eq!(patched, 0); - assert_eq!(&code[..LOAD_LEN], &load(reg)); - assert_eq!(code[LOAD_LEN], 0xC3); - continue; - } - assert_eq!(patched, 1, "r{reg}"); - // `call thunk[reg]`, then a nop that keeps the length at 9. - assert_eq!(code[0], 0xE8, "r{reg}"); - let rel = i64::from(i32::from_le_bytes(code[1..5].try_into().unwrap())); - let callee = (AT + 5) as i64 + rel; - assert_eq!( - callee, - (BLOCK + usize::from(reg) * THUNK_SIZE) as i64, - "r{reg}" - ); - assert_eq!(code[5..9], [0x0F, 0x1F, 0x40, 0x00], "r{reg}"); - assert_eq!(code[9], 0xC3, "r{reg}"); - } - } - - #[test] - fn other_nine_byte_windows_are_left_alone() { - // Each differs from the load in one field: the segment, the opcode, - // the ModRM's mod, the displacement, or the SIB's index. - let cases = [ - [0x64, 0x48, 0x8B, 0x04, 0x25, 0x58, 0, 0, 0], // fs: - [0x65, 0x48, 0x8A, 0x04, 0x25, 0x58, 0, 0, 0], // mov r8, r/m8 - [0x65, 0x48, 0x8B, 0x44, 0x25, 0x58, 0, 0, 0], // mod 01 - [0x65, 0x48, 0x8B, 0x04, 0x25, 0x58, 0, 0, 1], // offset 1 - [0x65, 0x48, 0x8B, 0x04, 0x26, 0x58, 0, 0, 0], // [rsi + 0x58] - ]; - for case in cases { - let mut code = case.to_vec(); - assert_eq!(patch(&mut code, 0x1000, 0x2000), 0, "{case:02X?}"); - assert_eq!(code, case, "{case:02X?}"); - } - } - - #[test] - fn a_window_short_of_a_load_is_not_read() { - // Eight bytes: one short of a whole load, and too short to match. - let mut code = load(5)[..LOAD_LEN - 1].to_vec(); - assert_eq!(patch(&mut code, 0x1000, 0x2000), 0); - assert_eq!(code, load(5)[..LOAD_LEN - 1]); - assert_eq!(patch(&mut [], 0x1000, 0x2000), 0); - } - - #[test] - fn loads_back_to_back_are_each_patched_once() { - let mut code = [load(1), load(9), load(2)].concat(); - assert_eq!(patch(&mut code, 0x1000, 0x2000), 3); - // The second pass finds calls and nops where the loads were. - assert_eq!(patch(&mut code, 0x1000, 0x2000), 0); - } - - #[test] - fn each_thunk_loads_the_array_and_adds_the_slots_offset() { - const INDEX: u32 = 1087; - let block = thunks(near(tls_array as *const () as usize, 0).unwrap(), INDEX).unwrap(); - // SAFETY: `block` is one page of ours, readable; `thunks` made it - // read-execute. - let bytes = unsafe { std::slice::from_raw_parts(block as *const u8, 4096) }; - for reg in 0..16u8 { - let slot = &bytes[usize::from(reg) * THUNK_SIZE..][..THUNK_SIZE]; - let (high, low) = (reg >> 3, reg & 7); - let mut thunk = vec![ - 0x65, - 0x48 | high << 2, - 0x8B, - low << 3 | 4, - 0x25, - 0x58, - 0, - 0, - 0, - // lea r, [r + index * 8]; the SIB says r12/rsp as the base. - 0x48 | high << 2 | high, - 0x8D, - 0x80 | low << 3 | low, - ]; - if low == 4 { - thunk.push(0x24); - } - thunk.extend((INDEX * 8).to_le_bytes()); - thunk.push(0xC3); - assert!(thunk.len() <= THUNK_SIZE); - assert_eq!(&slot[..thunk.len()], &thunk[..], "r{reg}"); - // One thunk's bytes must not run into the next thunk's. - assert!(slot[thunk.len()..].iter().all(|&b| b == 0), "r{reg}"); - } - // Running one only adds to the array pointer (it never reads the - // slot), so any index is safe to check here. - // SAFETY: the page is executable and the thunk ends in `ret`. - let rax: extern "system" fn() -> usize = unsafe { std::mem::transmute(block) }; - assert_eq!(rax(), tls_array() + INDEX as usize * 8); - } - - #[test] - fn near_stays_within_rel32_reach_and_writable() { - let base = tls_array as *const () as usize; - let page = near(base, 0).unwrap(); - assert!((page as usize).abs_diff(base) <= 1 << 30); - assert!(near(base, (1 << 30) - 1).is_ok()); - assert!(near(base, 1 << 30).is_err()); - // SAFETY: a fresh page of ours, writable as `near` promises. - unsafe { - page.write(0xA5); - assert_eq!(page.read(), 0xA5); - } - } - - /// A synthetic mapped image of the shape `redirect` expects: a TLS - /// directory at 0x1000 naming an index `u32` at 0x1100, and one - /// executable section at 0x2000 holding `mov rax, gs:[0x58]; ret`. - /// Only the layout is synthetic; `redirect` is what reads it. - struct Synthetic { - base: *mut u8, - info: ImageInfo, - index: *mut u32, - code: *mut u8, - } - - /// What the header declares, and so what `redirect` may touch. - const SIZE_OF_IMAGE: u32 = 0x2_0000; - /// What is mapped: a page more, so a test can name a plausible index - /// just past the declared image. - const MAPPED: usize = 0x2_1000; - const DIRECTORY: usize = 0x1000; - const INDEX: usize = 0x1100; - const TEXT: usize = 0x2000; - /// `mov rax, gs:[0x58]; ret`. - const CODE: [u8; 10] = [0x65, 0x48, 0x8B, 0x04, 0x25, 0x58, 0, 0, 0, 0xC3]; - /// `IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ`. - const TEXT_FLAGS: u32 = 0x6000_0020; - - impl Synthetic { - /// `tls_index` is the index the OS "wrote" for the image. - fn new(tls_index: u32) -> Self { - let text = SectionInfo { - name: ".text".into(), - rva: TEXT as u32, - virtual_size: 0x10, - file_offset: 0, - file_size: 0x10, - characteristics: TEXT_FLAGS, - }; - // SAFETY: a fresh mapping of ours, filled in as the loader - // would have left it. - unsafe { - let base = VirtualAlloc( - std::ptr::null(), - MAPPED, - MEM_COMMIT | MEM_RESERVE, - PAGE_READWRITE, - ) - .cast::(); - assert!(!base.is_null()); - let index = base.add(INDEX).cast::(); - index.write(tls_index); - // `IMAGE_TLS_DIRECTORY64`: raw data start and end, the - // address of the index, the callbacks, then zero fill. - let fields = [0u64, 0, index as u64, 0, 0, 0]; - for (i, field) in fields.into_iter().enumerate() { - base.add(DIRECTORY).cast::().add(i).write(field); - } - base.add(TEXT) - .copy_from_nonoverlapping(CODE.as_ptr(), CODE.len()); - let mut old = 0; - let exec = - VirtualProtect(base.add(TEXT).cast(), 0x1000, PAGE_EXECUTE_READ, &mut old); - assert_ne!(exec, 0); - Self { - base, - info: ImageInfo { - machine: victory_pe::MACHINE_AMD64, - characteristics: 0x0022, - timestamp: 0, - subsystem: 3, - dll_characteristics: 0, - image_base: base as u64, - size_of_image: SIZE_OF_IMAGE, - entry_rva: 0, - stack_reserve: 0, - stack_commit: 0, - sections: vec![text], - imports: Vec::new(), - delay_imports: Vec::new(), - exports: Vec::new(), - tls: Some(TlsInfo { - directory_rva: DIRECTORY as u32, - callbacks_va: 0, - callback_rvas: Vec::new(), - }), - has_relocations: false, - has_exception_table: false, - has_load_config: false, - codeview: None, - }, - index, - code: base.add(TEXT), - } - } - } - - fn try_patched(&self) -> Result { - // SAFETY: `info` describes this mapping, and nothing runs it. - unsafe { redirect(self.base as usize, &self.info) } - } - - fn patched(&self) -> usize { - self.try_patched().unwrap() - } - - fn index_value(&self) -> u32 { - // SAFETY: the index is in our mapping, and readable. - unsafe { self.index.read() } - } - - fn code_bytes(&self) -> [u8; N] { - // SAFETY: the text page is ours, and `N` is inside it. - unsafe { std::ptr::read(self.code.cast::<[u8; N]>()) } - } - - /// Points the directory's `AddressOfIndex` at `va` instead. - fn set_index_pointer(&mut self, va: u64) { - // SAFETY: the directory is in our mapping, still writable. - unsafe { self.base.add(DIRECTORY).cast::().add(2).write(va) }; - } - - /// Where the header says the image ends, plus `offset` bytes. - fn past_image(&self, offset: usize) -> *mut u64 { - // SAFETY: inside the mapping, which is `MAPPED` long. - unsafe { self.base.add(SIZE_OF_IMAGE as usize + offset).cast() } - } - } - - impl Drop for Synthetic { - fn drop(&mut self) { - // SAFETY: the mapping is ours, and nothing uses it any more. - unsafe { VirtualFree(self.base.cast(), 0, MEM_RELEASE) }; - } - } - - #[test] - fn a_redirected_image_yields_the_slot_the_os_gave_it() { - let image = Synthetic::new(5); - assert_eq!(image.patched(), 1); - let code = image.code_bytes::<10>(); - assert_eq!(code[0], 0xE8); - assert_eq!(code[5..9], [0x0F, 0x1F, 0x40, 0x00]); - assert_eq!(code[9], 0xC3); - // `_tls_index` is 0 from here on, as CRT code inside a DLL expects. - assert_eq!(image.index_value(), 0); - // The patched load returns the slot the OS assigned the image. - // SAFETY: the patched page is executable, and ends in `ret`. - let run: extern "system" fn() -> usize = unsafe { std::mem::transmute(image.code) }; - assert_eq!(run(), tls_array() + 5 * 8); - } - - #[test] - fn index_zero_needs_no_patches() { - let image = Synthetic::new(0); - assert_eq!(image.patched(), 0); - assert_eq!(image.code_bytes::<10>(), CODE); - } - - #[test] - fn an_empty_executable_section_does_not_stop_the_rest() { - let mut image = Synthetic::new(5); - image.info.sections.push(SectionInfo { - name: ".empty".into(), - rva: 0x3000, - virtual_size: 0, - file_offset: 0, - file_size: 0, - characteristics: TEXT_FLAGS, - }); - // `VirtualProtect` refuses a zero length; that must not abort the - // redirect of the sections that do hold code. - assert_eq!(image.patched(), 1); - assert_eq!(image.index_value(), 0); - } - - #[test] - fn an_index_no_loader_assigns_is_an_error() { - // `index * 8` overflows `u32` here; the index is read from the image. - let image = Synthetic::new(u32::MAX); - assert!(image.try_patched().is_err()); - assert_eq!(image.code_bytes::<10>(), CODE); - } - - #[test] - fn an_index_outside_the_image_is_not_written() { - // The directory may name anything; following it would zero a `u32` - // that is not the image's. - let outside = Box::into_raw(Box::new(0x5A5A_u32)); - let mut image = Synthetic::new(5); - image.set_index_pointer(outside as u64); - assert!(image.try_patched().is_err()); - // SAFETY: `outside` is still ours, and allocated. - assert_eq!(unsafe { outside.read() }, 0x5A5A); - // SAFETY: allocated above, never aliased. - unsafe { drop(Box::from_raw(outside)) }; - } - - #[test] - fn a_directory_outside_the_image_is_an_error() { - // The directory sits 8 bytes before the declared end, so its index - // field is past it: reading that field must stop there, not follow - // a header value into memory the image does not own. - let outside = Box::into_raw(Box::new(7_u32)); - let mut image = Synthetic::new(5); - // What the unchecked read would have found 16 bytes in: a readable - // index of 7, just past the declared image. - // SAFETY: inside our mapping, past what the header declares. - unsafe { image.past_image(8).write(outside as u64) }; - image.info.tls.as_mut().unwrap().directory_rva = SIZE_OF_IMAGE - 8; - assert!(image.try_patched().is_err()); - // SAFETY: `outside` is still ours, and allocated. - assert_eq!(unsafe { outside.read() }, 7); - // SAFETY: allocated above, never aliased. - unsafe { drop(Box::from_raw(outside)) }; - } - - #[test] - fn an_image_without_tls_needs_no_redirect() { - let mut image = Synthetic::new(5); - image.info.tls = None; - assert_eq!(image.patched(), 0); - assert_eq!(image.code_bytes::<10>(), CODE); - } } diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index 27a84dd..e709d11 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -82,14 +82,7 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result { // A DLL indexes its TLS properly; only an exe assumes index 0. if !loaded.info.is_dll() { // SAFETY: just mapped, and no title code has run. - if let Err(error) = unsafe { crate::tls::redirect(loaded.base(), &loaded.info) } { - // Nothing has seen this module yet (`threads::mapped` is below), - // so a failed load must not leave it mapped for the life of the - // process. - // SAFETY: no title code has run and the module is not registered. - unsafe { FreeLibrary(module) }; - return Err(error); - } + unsafe { crate::tls::redirect(loaded.base(), &loaded.info) }?; } tracing::info!( base = format_args!("{:#x}", loaded.base()), @@ -294,20 +287,10 @@ impl LoadedImage { /// Protects and restores each slot on its own: import tables can sit in /// sections with different protections (delay-load tables in `.didat`). fn write_slots(&self, slots: &[(u32, usize)]) -> Result<()> { - // The RVAs come from the image's own tables, which `victory-pe` - // checks when it parses them. Check again before touching memory: - // an RVA past the image would write into whatever the loader mapped - // next, and no `VirtualProtect` failure would necessarily stop it. - let size = u64::from(self.info.size_of_image); - for &(rva, _) in slots { - if u64::from(rva) + 8 > size { - bail!("IAT slot {rva:#x} is outside the image ({size:#x} bytes)"); - } - } for &(rva, address) in slots { let slot = (self.base() + rva as usize) as *mut u64; let mut old = 0; - // SAFETY: the checked slot lies inside the image. + // SAFETY: the parser only yields slots inside the image. if unsafe { VirtualProtect(slot as *const c_void, 8, PAGE_READWRITE, &mut old) } == 0 { bail!( "VirtualProtect(IAT slot {rva:#x}) failed: {}", @@ -337,18 +320,8 @@ impl LoadedImage { unsafe fn tls_callbacks(&self, reason: u32, reserved: *mut c_void) { let Some(tls) = &self.info.tls else { return }; for &rva in &tls.callback_rvas { - // A callback is code inside the image; RVA 0 is the header, and - // anything past the image belongs to another mapping. Calling - // either would run memory the image does not own. - if rva == 0 || u64::from(rva) >= u64::from(self.info.size_of_image) { - tracing::warn!( - rva = format_args!("{rva:#x}"), - "TLS callback outside the image, skipped" - ); - continue; - } type TlsCallback = unsafe extern "system" fn(*mut c_void, u32, *mut c_void); - // SAFETY: the RVA is inside the image and came from its TLS directory. + // SAFETY: the RVA came from the image's own TLS directory. let callback: TlsCallback = unsafe { std::mem::transmute(self.base() + rva as usize) }; // SAFETY: the caller guarantees imports are bound. unsafe { callback(self.module, reason, reserved) }; @@ -400,19 +373,8 @@ impl LoadedImage { if !dll_main || !self.info.is_dll() || self.info.entry_rva == 0 { return None; } - // An entry point outside the image cannot be this image's `DllMain`. - // Report it the way a `DllMain` that refuses the process does, - // rather than call into whatever is mapped past the image. - if u64::from(self.info.entry_rva) >= u64::from(self.info.size_of_image) { - tracing::error!( - entry = format_args!("{:#x}", self.info.entry_rva), - size = format_args!("{:#x}", self.info.size_of_image), - "DllMain outside the image" - ); - return Some(0); - } type DllMain = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; - // SAFETY: the entry RVA is inside the image and came from its header. + // SAFETY: the entry RVA came from the original image header. let main: DllMain = unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) }; // SAFETY: forwarded from the caller. @@ -433,12 +395,6 @@ impl LoadedImage { if self.info.entry_rva == 0 { bail!("image has no entry point"); } - if u64::from(self.info.entry_rva) >= u64::from(self.info.size_of_image) { - bail!( - "entry point {:#x} is outside the image", - self.info.entry_rva - ); - } let stack = usize::try_from(self.info.stack_reserve) .unwrap_or(usize::MAX) .max(1 << 20); @@ -474,547 +430,3 @@ impl LoadedImage { unsafe { FreeLibrary(self.module) }; } } - -#[cfg(test)] -mod tests { - use std::sync::atomic::Ordering; - - use victory_pe::{ImportEntry, ImportModule, ImportSymbol, TlsInfo}; - use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; - use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, - PAGE_READONLY, PAGE_READWRITE, VirtualAlloc, VirtualFree, VirtualQuery, - }; - - use super::*; - use crate::{disable_thread_calls, unimplemented_call_count}; - - const PAGE: usize = 0x1000; - - /// A committed scratch block standing in for a mapped image. - fn alloc(pages: usize, protect: u32) -> usize { - // SAFETY: a fresh anonymous allocation, freed once by `free`. - let at = unsafe { - VirtualAlloc( - std::ptr::null(), - pages * PAGE, - MEM_COMMIT | MEM_RESERVE, - protect, - ) - } as usize; - assert_ne!(at, 0, "VirtualAlloc failed"); - at - } - - fn free(at: usize) { - // SAFETY: `at` is a live block from `alloc`, freed once. - unsafe { VirtualFree(at as *mut c_void, 0, MEM_RELEASE) }; - } - - fn protection(at: usize) -> u32 { - // SAFETY: a zeroed output buffer of the type the call fills. - let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - // SAFETY: `at` is inside a live allocation; `info` is sized for the call. - let n = unsafe { VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; - assert_ne!(n, 0, "VirtualQuery failed"); - info.Protect - } - - fn put(at: usize, code: &[u8]) { - // SAFETY: callers pass a range inside a live executable allocation. - unsafe { std::ptr::copy_nonoverlapping(code.as_ptr(), at as *mut u8, code.len()) }; - } - - /// `mov rax, ; inc qword ptr [rax]; ret`. - fn bump(counter: &'static AtomicU64) -> Vec { - let mut code = vec![0x48, 0xB8]; - code.extend_from_slice(&(counter as *const AtomicU64 as u64).to_le_bytes()); - code.extend_from_slice(&[0x48, 0xFF, 0x00]); - code.push(0xC3); - code - } - - /// `mov eax, ; ret`. - fn ret(value: u32) -> Vec { - let mut code = vec![0xB8]; - code.extend_from_slice(&value.to_le_bytes()); - code.push(0xC3); - code - } - - fn import(dll: &str, rva: u32) -> ImportModule { - ImportModule { - dll: dll.to_owned(), - entries: vec![ImportEntry { - symbol: ImportSymbol::Name { - hint: 0, - name: format!("f{rva:x}"), - }, - iat_slot_rva: rva, - }], - } - } - - fn info(size_of_image: u32) -> ImageInfo { - ImageInfo { - machine: victory_pe::MACHINE_AMD64, - characteristics: victory_pe::layout::file_flags::DLL, - timestamp: 0, - subsystem: victory_pe::layout::subsystem::WINDOWS_CUI, - dll_characteristics: 0, - image_base: 0, - size_of_image, - entry_rva: 0, - stack_reserve: 0, - stack_commit: 0, - sections: Vec::new(), - imports: Vec::new(), - delay_imports: Vec::new(), - exports: Vec::new(), - tls: None, - has_relocations: false, - has_exception_table: false, - has_load_config: false, - codeview: None, - } - } - - /// A `LoadedImage` whose `module` is a scratch allocation, not a real PE. - fn image_at(base: usize, info: ImageInfo) -> LoadedImage { - LoadedImage { - module: base as *mut c_void, - path: PathBuf::new(), - info, - } - } - - fn slot(image: &LoadedImage, rva: u32) -> u64 { - // SAFETY: every slot the tests read lies inside a live allocation. - unsafe { ((image.base() + rva as usize) as *const u64).read_volatile() } - } - - fn found(address: usize) -> Resolution { - Resolution::Found { - address, - provenance: Provenance::Hle, - } - } - - fn prepared_own() -> PreparedImage { - let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); - prepare(&original).unwrap() - } - - fn module_by_name(name: &str) -> usize { - let wide: Vec = name.encode_utf16().chain(Some(0)).collect(); - // SAFETY: a NUL-terminated UTF-16 name; the query takes no reference. - unsafe { GetModuleHandleW(wide.as_ptr()) as usize } - } - - struct Fixed(Resolution); - - impl ImportResolver for Fixed { - fn resolve(&self, _: &str, _: &ImportSymbol) -> Resolution { - self.0 - } - } - - /// Provenance per DLL name, as a title's imports arrive. - struct ByDll; - - impl ImportResolver for ByDll { - fn resolve(&self, dll: &str, _: &ImportSymbol) -> Resolution { - let found = match dll.to_ascii_lowercase().as_str() { - "hle.dll" => Some((0x1111, Provenance::Hle)), - "host.dll" => Some((0x2222, Provenance::Host)), - "title.dll" => Some((0x3333, Provenance::Title)), - _ => None, - }; - found.map_or(Resolution::Missing, |(address, provenance)| { - Resolution::Found { - address, - provenance, - } - }) - } - } - - #[test] - fn maps_and_unloads_a_prepared_copy() { - let prepared = prepared_own(); - let dir = tempfile::tempdir().unwrap(); - let image = load(&prepared, dir.path()).unwrap(); - assert_ne!(image.base(), 0); - assert_eq!(image.base() % PAGE, 0, "the loader page-aligns the mapping"); - assert_eq!(image.info().import_count(), prepared.info.import_count()); - assert_eq!( - std::fs::read(dir.path().join(prepared.file_name())).unwrap(), - prepared.bytes - ); - // The prepared copy is registered as mapped, and keeps its static TLS. - assert_eq!(disable_thread_calls(image.base()), Some(false)); - // SAFETY: never attached, and no pointer into it outlives this test. - unsafe { image.unload() }; - } - - #[test] - fn write_if_changed_rewrites_only_when_the_bytes_differ() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("victory-image-test.dll"); - write_if_changed(&path, b"one").unwrap(); - let read_only = |on: bool| { - let mut permissions = std::fs::metadata(&path).unwrap().permissions(); - permissions.set_readonly(on); - std::fs::set_permissions(&path, permissions).unwrap(); - }; - // Identical bytes: no write happens, so even a read-only file is fine - // (replacing a read-only file on Windows fails). - read_only(true); - write_if_changed(&path, b"one").unwrap(); - read_only(false); - write_if_changed(&path, b"two").unwrap(); - assert_eq!(std::fs::read(&path).unwrap(), b"two"); - assert!( - !path.with_extension("tmp").exists(), - "the temporary file is renamed, not left behind" - ); - } - - #[test] - fn binds_imports_and_delay_imports_by_provenance() { - let base = alloc(1, PAGE_READONLY); - let mut info = info(PAGE as u32); - info.imports = vec![ - import("hle.dll", 0x100), - import("host.dll", 0x108), - import("title.dll", 0x110), - ]; - info.delay_imports = vec![import("missing.dll", 0x118)]; - let image = image_at(base, info); - let report = image - .bind_imports(&ByDll, UnimplementedPolicy::ReturnZero) - .unwrap(); - assert_eq!((report.hle, report.host, report.title), (1, 1, 1)); - assert_eq!(report.missing.len(), 1); - assert_eq!(report.missing[0].dll, "missing.dll"); - assert_eq!(report.missing[0].symbol, "f118"); - assert_eq!(slot(&image, 0x100), 0x1111); - assert_eq!(slot(&image, 0x108), 0x2222); - assert_eq!(slot(&image, 0x110), 0x3333); - assert_ne!(slot(&image, 0x118), 0, "the delay-import slot got a stub"); - assert_eq!( - protection(base + 0x100), - PAGE_READONLY, - "the slot's protection is restored" - ); - free(base); - } - - #[test] - fn binding_restores_the_protection_of_each_section() { - let base = alloc(2, PAGE_READWRITE); - let mut old = 0; - // SAFETY: the second page is inside the allocation. - let changed = unsafe { - VirtualProtect( - (base + PAGE) as *const c_void, - PAGE, - PAGE_READONLY, - &mut old, - ) - }; - assert_ne!(changed, 0); - let before = (protection(base + 0x100), protection(base + PAGE + 0x100)); - assert_eq!(before, (PAGE_READWRITE, PAGE_READONLY)); - let mut info = info((2 * PAGE) as u32); - info.imports = vec![import("a.dll", 0x100), import("b.dll", PAGE as u32 + 0x100)]; - let image = image_at(base, info); - let report = image - .bind_imports(&Fixed(found(0x1234)), UnimplementedPolicy::ReturnZero) - .unwrap(); - assert_eq!(report.hle, 2); - assert_eq!(slot(&image, 0x100), 0x1234); - assert_eq!(slot(&image, PAGE as u32 + 0x100), 0x1234); - assert_eq!( - (protection(base + 0x100), protection(base + PAGE + 0x100)), - before - ); - free(base); - } - - #[test] - fn binding_no_imports_does_nothing() { - let base = alloc(1, PAGE_READWRITE); - let image = image_at(base, info(PAGE as u32)); - let report = image - .bind_imports(&Fixed(Resolution::Missing), UnimplementedPolicy::Trap) - .unwrap(); - assert_eq!((report.hle, report.host, report.title), (0, 0, 0)); - assert!(report.missing.is_empty()); - free(base); - } - - #[test] - fn unresolved_imports_get_a_callable_stub() { - let base = alloc(1, PAGE_READWRITE); - let mut info = info(PAGE as u32); - info.imports = vec![ImportModule { - dll: "missing.dll".into(), - entries: vec![ - ImportEntry { - symbol: ImportSymbol::Name { - hint: 0, - name: "one".into(), - }, - iat_slot_rva: 0x100, - }, - ImportEntry { - symbol: ImportSymbol::Ordinal(7), - iat_slot_rva: 0x108, - }, - ], - }]; - let image = image_at(base, info); - let report = image - .bind_imports(&Fixed(Resolution::Missing), UnimplementedPolicy::ReturnZero) - .unwrap(); - assert_eq!(report.missing.len(), 2); - assert_eq!(report.missing[0].dll, "missing.dll"); - assert_eq!(report.missing[0].symbol, "one"); - assert_eq!(report.missing[1].symbol, "#7"); - let before = unimplemented_call_count(); - for rva in [0x100, 0x108] { - // SAFETY: the loader wrote a stub to this slot; the stub ignores - // its arguments and returns 0 under `ReturnZero`. - let stub: unsafe extern "system" fn() -> u64 = - unsafe { std::mem::transmute::(slot(&image, rva)) }; - // SAFETY: as above. - assert_eq!(unsafe { stub() }, 0); - } - assert!(unimplemented_call_count() >= before + 2); - free(base); - } - - #[test] - fn an_iat_slot_outside_the_image_is_refused_before_memory_is_touched() { - let base = alloc(2, PAGE_READWRITE); - const CANARY: u64 = 0xDEAD_BEEF_CAFE_F00D; - // SAFETY: the second page is inside the allocation. - unsafe { ((base + PAGE) as *mut u64).write(CANARY) }; - for rva in [PAGE as u32, PAGE as u32 - 4] { - let mut info = info(PAGE as u32); - info.imports = vec![import("x.dll", rva)]; - let image = image_at(base, info); - let error = image - .bind_imports(&Fixed(found(0x1111)), UnimplementedPolicy::ReturnZero) - .unwrap_err(); - assert!(error.to_string().contains("outside the image"), "{error:#}"); - // SAFETY: the canary is inside the allocation. - let canary = unsafe { ((base + PAGE) as *const u64).read() }; - assert_eq!( - canary, CANARY, - "nothing past the image was written (slot {rva:#x})" - ); - } - // The last slot that fits wholly inside the image is written. - let mut info = info(PAGE as u32); - info.imports = vec![import("x.dll", PAGE as u32 - 8)]; - let image = image_at(base, info); - image - .bind_imports(&Fixed(found(0x1111)), UnimplementedPolicy::ReturnZero) - .unwrap(); - assert_eq!(slot(&image, PAGE as u32 - 8), 0x1111); - free(base); - } - - #[test] - fn a_failed_tls_redirect_unmaps_the_image() { - let mut original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); - // A unique build hash, so the module name belongs to this test alone. - original[16] ^= 0xFF; - let prepared = prepare(&original).unwrap(); - assert!(!prepared.info.is_dll()); - assert!( - prepared.info.tls.is_some(), - "the test binary uses static TLS" - ); - let mut info = prepared.info.clone(); - // The TLS thunk search refuses images this large, so `redirect` fails - // after `load` has already mapped the copy. - info.size_of_image = 1 << 30; - let prepared = PreparedImage { - info, - bytes: prepared.bytes.clone(), - original_hash: prepared.original_hash, - }; - let name = prepared.file_name(); - assert_eq!(module_by_name(&name), 0, "no module with this name yet"); - let dir = tempfile::tempdir().unwrap(); - let error = load(&prepared, dir.path()).unwrap_err(); - let text = format!("{error:#}").to_ascii_lowercase(); - assert!( - text.contains("tls"), - "expected the TLS redirect to fail: {text}" - ); - assert_eq!( - module_by_name(&name), - 0, - "a load that failed after mapping must unmap" - ); - } - - static HEADER_CALLS: AtomicU64 = AtomicU64::new(0); - static IMAGE_CALLS: AtomicU64 = AtomicU64::new(0); - static OUTSIDE_CALLS: AtomicU64 = AtomicU64::new(0); - - #[test] - fn tls_callbacks_outside_the_image_are_not_called() { - let base = alloc(2, PAGE_EXECUTE_READWRITE); - put(base, &bump(&HEADER_CALLS)); - put(base + 0x800, &bump(&IMAGE_CALLS)); - put(base + PAGE, &bump(&OUTSIDE_CALLS)); - let mut info = info(PAGE as u32); - info.tls = Some(TlsInfo { - directory_rva: 0, - callbacks_va: 0, - callback_rvas: vec![0, 0x800, PAGE as u32], - }); - let image = image_at(base, info); - HEADER_CALLS.store(0, Ordering::SeqCst); - IMAGE_CALLS.store(0, Ordering::SeqCst); - OUTSIDE_CALLS.store(0, Ordering::SeqCst); - // SAFETY: the "callbacks" only bump a static counter and return. - unsafe { image.run_tls_callbacks(DLL_PROCESS_ATTACH) }; - assert_eq!( - IMAGE_CALLS.load(Ordering::SeqCst), - 1, - "the in-image callback runs" - ); - assert_eq!( - HEADER_CALLS.load(Ordering::SeqCst), - 0, - "the image header is not code" - ); - assert_eq!( - OUTSIDE_CALLS.load(Ordering::SeqCst), - 0, - "nothing past the image is called" - ); - free(base); - } - - #[test] - fn a_dll_main_outside_the_image_does_not_run() { - let base = alloc(2, PAGE_EXECUTE_READWRITE); - put(base + 0x800, &ret(7)); - put(base + PAGE, &ret(7)); - let mut info = info(PAGE as u32); - info.entry_rva = PAGE as u32; - let mut image = image_at(base, info.clone()); - // SAFETY: the entry point (if it ran) only returns 7. - let outcome = unsafe { image.notify(DLL_PROCESS_ATTACH, true, std::ptr::null_mut()) }; - assert_eq!( - outcome, - Some(0), - "an entry point outside the image is reported as DllMain failing" - ); - info.entry_rva = 0x800; - image.info = info; - // SAFETY: as above; this entry point is inside the image. - let outcome = unsafe { image.notify(DLL_PROCESS_ATTACH, true, std::ptr::null_mut()) }; - assert_eq!(outcome, Some(7)); - free(base); - } - - #[test] - fn spawn_main_refuses_an_entry_outside_the_image() { - let base = alloc(2, PAGE_EXECUTE_READWRITE); - put(base + PAGE, &ret(9)); - let mut info = info(PAGE as u32); - info.characteristics = 0; // an exe, as the main image is - info.entry_rva = PAGE as u32; - let image = Arc::new(image_at(base, info)); - // SAFETY: the entry point (if it ran) only returns 9. - match unsafe { image.spawn_main(Vec::new()) } { - Err(error) => assert!(error.to_string().contains("outside the image"), "{error:#}"), - Ok(thread) => { - let code = thread.join().unwrap(); - free(base); - panic!("an entry point outside the image ran and returned {code:?}"); - } - } - free(base); - } - - #[test] - fn exports_are_looked_up_by_name() { - let title = tempfile::tempdir().unwrap(); - std::fs::copy( - r"C:\Windows\System32\version.dll", - title.path().join("v.dll"), - ) - .unwrap(); - let loaded = load_title_dll("v.dll", title.path(), title.path(), &|_| true).unwrap(); - assert_eq!(loaded.len(), 1); - let image = &loaded[0].1; - assert!(image.export("GetFileVersionInfoW").is_some()); - assert!(image.export("NoSuchExport").is_none()); - assert!( - image.export("Get\0FileVersionInfoW").is_none(), - "an interior NUL is refused" - ); - assert!( - image.export("getfileversioninfow").is_none(), - "export names are case-sensitive" - ); - assert!( - image - .export_symbol(&ImportSymbol::Name { - hint: 0, - name: "GetFileVersionInfoW".into(), - }) - .is_some() - ); - assert!(image.export_symbol(&ImportSymbol::Ordinal(0)).is_none()); - for (_, dll) in loaded { - // SAFETY: never attached, and no pointer into it outlives the test. - unsafe { dll.unload() }; - } - } - - #[test] - fn title_dlls_are_mapped_once_and_named_in_lowercase() { - let title = tempfile::tempdir().unwrap(); - let cache = tempfile::tempdir().unwrap(); - std::fs::copy( - r"C:\Windows\System32\version.dll", - title.path().join("Late.dll"), - ) - .unwrap(); - let mut main = info(PAGE as u32); - main.imports = vec![import("Late.dll", 0), import("LATE.DLL", 0)]; - main.delay_imports = vec![import("late.dll", 0)]; - let dlls = - load_title_dlls(&main, title.path(), cache.path(), &|dll| dll == "late.dll").unwrap(); - assert_eq!(dlls.len(), 1, "one mapping for three spellings"); - assert_eq!(dlls[0].0, "late.dll"); - assert!(dlls[0].1.export("GetFileVersionInfoW").is_some()); - // `wanted` refuses it, or the folder has no such file: nothing maps. - assert!( - load_title_dlls(&main, title.path(), cache.path(), &|_| false) - .unwrap() - .is_empty() - ); - let mut absent = info(PAGE as u32); - absent.imports = vec![import("absent.dll", 0)]; - assert!( - load_title_dlls(&absent, title.path(), cache.path(), &|_| true) - .unwrap() - .is_empty() - ); - for (_, dll) in dlls { - // SAFETY: never attached, and no pointer into it outlives the test. - unsafe { dll.unload() }; - } - } -} diff --git a/crates/victory-loader/tests/load_probe.rs b/crates/victory-loader/tests/load_probe.rs index ad225d0..cf1111b 100644 --- a/crates/victory-loader/tests/load_probe.rs +++ b/crates/victory-loader/tests/load_probe.rs @@ -19,100 +19,22 @@ fn workspace_root() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..") } -/// Set to a prebuilt `hle_probe.dll` to load it instead of building one. -const PREBUILT_PROBE: &str = "VICTORY_HLE_PROBE_DLL"; - -/// Whether we run under Wine (its ntdll exports `wine_get_version`). -fn under_wine() -> bool { - // SAFETY: NUL-terminated strings; ntdll is always loaded. - unsafe { - let ntdll = LoadLibraryA(c"ntdll.dll".as_ptr().cast()); - !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() - } -} - -/// The fixture to load, or `None` when it cannot be had here. -/// -/// Normally it is built into its own target dir under `CARGO_TARGET_TMPDIR` -/// (the outer cargo holds the lock on the main one while tests run), so it -/// follows `CARGO_TARGET_DIR` and `build.target-dir` like the rest of the -/// build. Under Wine, as when a test exe cross-built on Linux is run by Wine -/// or Proton, the `cargo` that built the test is a host program the guest -/// cannot run, so the test is skipped unless the fixture was built -/// beforehand, e.g. with -/// `cargo xwin build --manifest-path tests/fixtures/hle-probe/Cargo.toml -/// --target x86_64-pc-windows-msvc` and its path in `VICTORY_HLE_PROBE_DLL`. -fn probe_dll() -> Option { - if let Some(path) = std::env::var_os(PREBUILT_PROBE).filter(|p| !p.is_empty()) { - let path = PathBuf::from(path); - // Under Wine a bare Unix path (`/home/...`) resolves against the - // current drive and silently misses; fail with the fix instead of a - // bare "not found" from the read below. - assert!( - path.is_file(), - "{PREBUILT_PROBE}={} is not a file; under Wine use its Windows \ - path, e.g. Z:/home/you/VIctory/tests/fixtures/hle-probe/target/\ - x86_64-pc-windows-msvc/debug/hle_probe.dll", - path.display() - ); - return Some(path); - } - if under_wine() { - eprintln!( - "skipping: under Wine the host cargo cannot build hle-probe; \ - set {PREBUILT_PROBE} to a prebuilt hle_probe.dll to run this test" - ); - return None; - } +/// Builds the fixture into its own target dir (the outer cargo holds the +/// lock on the main one while tests run), in the outer one's scratch folder +/// for tests, so that it follows `CARGO_TARGET_DIR` like the rest of the +/// build. +fn build_probe() -> PathBuf { let manifest = workspace_root().join("tests/fixtures/hle-probe/Cargo.toml"); let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("hle-probe"); - // Name the target: a `CARGO_BUILD_TARGET` or `build.target` from the - // environment or a user config would otherwise move the output under a - // triple directory the path below does not expect. The fixture's build - // script passes MSVC linker flags, hence `-msvc`. - let triple = format!("{}-pc-windows-msvc", std::env::consts::ARCH); - // The cargo that built this test, recorded at compile time. A test exe - // cross-built elsewhere and copied here names a cargo that is not on this - // machine; say so instead of a bare "not found" from the spawn below. - let cargo = Path::new(env!("CARGO")); - assert!( - cargo.is_file(), - "{} (the cargo that built this test) is not on this machine; build \ - hle-probe and set {PREBUILT_PROBE} to its hle_probe.dll", - cargo.display() - ); - let status = Command::new(cargo) - .args(["build", "--quiet", "--locked", "--manifest-path"]) + let status = Command::new(env!("CARGO")) + .args(["build", "--quiet", "--manifest-path"]) .arg(&manifest) - .args(["--target", &triple, "--target-dir"]) + .arg("--target-dir") .arg(&target) .status() - .unwrap_or_else(|e| panic!("running {}: {e}", cargo.display())); - assert!( - status.success(), - "building {} for {triple} failed ({status})", - manifest.display() - ); - let dll = target.join(&triple).join("debug").join("hle_probe.dll"); - assert!( - dll.is_file(), - "hle-probe built, but {} is missing", - dll.display() - ); - Some(dll) -} - -/// A stand-in title DLL: `version.dll` from the system directory. Built from -/// `%SystemRoot%` (Windows may not be on `C:`); the copy names both paths if -/// it fails. -fn copy_stand_in_dll(to: &Path) { - let windows = std::env::var_os("SystemRoot") - .filter(|p| !p.is_empty()) - .map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); - let from = windows.join("System32").join("version.dll"); - if let Err(e) = std::fs::copy(&from, to) { - panic!("copying {} to {}: {e}", from.display(), to.display()); - } + .expect("running cargo"); + assert!(status.success(), "building hle-probe failed"); + target.join("debug").join("hle_probe.dll") } extern "system" fn fake_xgameruntime_initialize() -> i32 { @@ -176,9 +98,7 @@ fn host(dll: &str, name: &str) -> Option { #[test] fn loads_binds_and_calls_probe() { - let Some(dll) = probe_dll() else { - return; - }; + let dll = build_probe(); let original = std::fs::read(&dll).unwrap(); let prepared = prepare(&original).unwrap(); @@ -210,7 +130,11 @@ fn loads_binds_and_calls_probe() { // The "title" ships victory-probe-title.dll: any real DLL will do. let title_dir = tempfile::tempdir().unwrap(); - copy_stand_in_dll(&title_dir.path().join("victory-probe-title.dll")); + std::fs::copy( + r"C:\Windows\System32\version.dll", + title_dir.path().join("victory-probe-title.dll"), + ) + .unwrap(); let dlls = victory_loader::load_title_dlls(image.info(), title_dir.path(), dir.path(), &|_| true) .unwrap(); @@ -327,7 +251,11 @@ fn maps_a_title_dll_the_title_loads_itself() { let title_dir = tempfile::tempdir().unwrap(); let cache = tempfile::tempdir().unwrap(); // Any real DLL will do; it imports only host DLLs, which are not in the folder. - copy_stand_in_dll(&title_dir.path().join("Late.dll")); + std::fs::copy( + r"C:\Windows\System32\version.dll", + title_dir.path().join("Late.dll"), + ) + .unwrap(); let load = |name: &str, wanted: &dyn Fn(&str) -> bool| { victory_loader::load_title_dll(name, title_dir.path(), cache.path(), wanted).unwrap() }; diff --git a/crates/victory-pe/src/image.rs b/crates/victory-pe/src/image.rs index 2489d27..fc8f0f6 100644 --- a/crates/victory-pe/src/image.rs +++ b/crates/victory-pe/src/image.rs @@ -410,9 +410,7 @@ mod tests { std::fs::read(std::env::current_exe().unwrap()).unwrap() } - #[cfg(windows)] #[test] - #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn parses_own_test_binary() { let info = ImageInfo::parse(&own_image()).unwrap(); assert_eq!(info.machine, MACHINE_AMD64); @@ -431,9 +429,7 @@ mod tests { assert!(info.tls.is_some()); } - #[cfg(windows)] #[test] - #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn rva_to_file_offset_maps_entry_point() { let data = own_image(); let info = ImageInfo::parse(&data).unwrap(); @@ -441,9 +437,7 @@ mod tests { assert!(off < data.len()); } - #[cfg(windows)] #[test] - #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn rva_to_file_offset_rejects_offsets_past_4_gib() { let mut info = ImageInfo::parse(&own_image()).unwrap(); let rva = info.sections[0].rva + 0x20; @@ -463,9 +457,7 @@ mod tests { assert!(ImageInfo::parse(&truncated).is_err()); } - #[cfg(windows)] #[test] - #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn rejects_iat_outside_image() { let mut data = own_image(); let dd = layout::data_directory_offset(&data, dir::IMPORT).unwrap(); diff --git a/crates/victory-shader/Cargo.toml b/crates/victory-shader/Cargo.toml index edfd1b9..3d0caf1 100644 --- a/crates/victory-shader/Cargo.toml +++ b/crates/victory-shader/Cargo.toml @@ -9,7 +9,7 @@ publish.workspace = true [dependencies] thiserror.workspace = true -miniz_oxide.workspace = true +zlib-rs.workspace = true [features] # Host D3D12 pipeline checks (`emit::host`). diff --git a/crates/victory-shader/src/bvh.rs b/crates/victory-shader/src/bvh.rs index 43fb195..9f54001 100644 --- a/crates/victory-shader/src/bvh.rs +++ b/crates/victory-shader/src/bvh.rs @@ -61,7 +61,7 @@ //! public software emulation of this instruction in the open-source Vulkan //! driver for this GPU family (box test and sorting network as there; the //! triangle test is the watertight one it uses, Woop, Benthin and Wald, -//! JCGT 2013), and agree with what Grand Theft Auto VI's own structure +//! JCGT 2013), and agree with what the title's own structure //! builder writes and its trace programs read. Not known from either: how //! the console rounds, which of two boxes entered at the same distance it //! returns first, and what it returns for a ray exactly through an edge diff --git a/crates/victory-shader/src/dxbc.rs b/crates/victory-shader/src/dxbc.rs index 05ca335..7a20963 100644 --- a/crates/victory-shader/src/dxbc.rs +++ b/crates/victory-shader/src/dxbc.rs @@ -65,32 +65,21 @@ const HEADER_SIZE: usize = 0x20; const MAX_PARTS: usize = 256; impl<'a> Container<'a> { - /// Declared byte length from a complete container header. The caller - /// still needs to read and parse the container's parts. - pub fn declared_len(header: &[u8]) -> Result { - if header.len() < HEADER_SIZE || &header[..4] != b"DXBC" { + pub fn parse(data: &'a [u8]) -> Result { + if data.len() < HEADER_SIZE || &data[0..4] != b"DXBC" { return Err(ShaderError::NotDxbc); } - let total = u32_at(header, 0x18)? as usize; - let count = u32_at(header, 0x1C)? as usize; - if count > MAX_PARTS { - return Err(ShaderError::Malformed("implausible part count")); - } - if total < HEADER_SIZE + 4 * count { - return Err(ShaderError::Malformed("container size disagrees with data")); - } - Ok(total) - } - - pub fn parse(data: &'a [u8]) -> Result { - let total = Self::declared_len(data)?; let digest = data[4..20].try_into().expect("16 bytes"); let version = (u16_at(data, 0x14)?, u16_at(data, 0x16)?); - if total > data.len() { + let total = u32_at(data, 0x18)? as usize; + if total > data.len() || total < HEADER_SIZE { return Err(ShaderError::Malformed("container size disagrees with data")); } let data = &data[..total]; let count = u32_at(data, 0x1C)? as usize; + if count > MAX_PARTS { + return Err(ShaderError::Malformed("implausible part count")); + } let mut parts = Vec::with_capacity(count); for i in 0..count { let offset = u32_at(data, HEADER_SIZE + 4 * i)? as usize; diff --git a/crates/victory-shader/src/emit/address_map.rs b/crates/victory-shader/src/emit/address_map.rs deleted file mode 100644 index ef3ee7e..0000000 --- a/crates/victory-shader/src/emit/address_map.rs +++ /dev/null @@ -1,61 +0,0 @@ -//! The address map: how a translated shader finds title memory at an -//! address it computes ([`crate::resource::GLOBAL`]), for the host to fill. -//! -//! A raw buffer bound as a root SRV, `t0` in -//! [`super::ADDRESS_MAP_SPACE`], when [`super::HostShader::address_map`] -//! is set: -//! -//! * a header of [`HEADER`] bytes: dword 0 is the number of ranges `n`, the -//! rest zero; -//! * then `n` entries of [`ENTRY`] bytes, sorted by start address and not -//! overlapping: the range's first title address (dwords 0 and 1, low -//! first), its length in bytes (dword 2), the descriptor heap index of a -//! raw UAV view (`R32_TYPELESS`, raw flag) holding its bytes (dword 3), -//! and the byte offset of the range's first byte in that view (dword 4); -//! dwords 5 to 7 are zero. -//! -//! The shader finds the last range starting at or below an address with a -//! binary search and reads through `ResourceDescriptorHeap[view]` (a -//! non-uniform index when lanes differ), so the views must be in the heap -//! bound with the map. An address no range covers reads zero. Root -//! descriptors are not bounds-checked: the buffer must hold all `n` -//! entries. - -/// Bytes before the first entry. -pub const HEADER: u32 = 16; -/// Bytes per entry. -pub const ENTRY: u32 = 32; - -/// One range of title memory and the view that holds it. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Range { - pub start: u64, - pub len: u32, - pub view: u32, - pub view_offset: u32, -} - -/// The map's dwords for `ranges`, which must be sorted by start and not -/// overlap. -pub fn encode(ranges: &[Range]) -> Vec { - debug_assert!( - ranges - .windows(2) - .all(|w| w[0].start + u64::from(w[0].len) <= w[1].start) - ); - let mut out = vec![0; (HEADER / 4) as usize]; - out[0] = ranges.len() as u32; - for r in ranges { - out.extend([ - r.start as u32, - (r.start >> 32) as u32, - r.len, - r.view, - r.view_offset, - 0, - 0, - 0, - ]); - } - out -} diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 0be6ef3..eff0ac0 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -5,16 +5,32 @@ //! it is written: functions, then constants (all at module level), then the //! instructions of `main` in block order. -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; + +pub mod census; +pub mod opt; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub(crate) struct Ty(u32); +/// What the lowering made an instruction for, where it says so (counted by +/// [`census`], nothing else reads it). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Tag { + /// The select that keeps a register's old value in lanes a guard masks. + Guard, + /// An index clamp the translation adds (the console has none). + Clamp, + /// The iteration counter and limit test the translation adds to a loop. + Counter, +} + #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum TypeDef { Void, Int(u32), Float, + Double, /// Pointee and address space. Ptr(Ty, u32), Struct(Option, Vec), @@ -208,6 +224,8 @@ pub(crate) struct Module { blocks: Vec, mds: Vec, named: Vec<(String, Vec)>, + /// See [`Tag`]: by instruction. + tags: HashMap, } impl Module { @@ -230,6 +248,9 @@ impl Module { pub fn float(&mut self) -> Ty { self.ty(TypeDef::Float) } + pub fn double(&mut self) -> Ty { + self.ty(TypeDef::Double) + } pub fn ptr(&mut self, to: Ty) -> Ty { self.ty(TypeDef::Ptr(to, 0)) } @@ -308,10 +329,6 @@ impl Module { /// Gives constant `old` the content of `new` (both stay valid). pub fn replace_const(&mut self, old: V, new: V) { if let (V::Const(o), V::Const(n)) = (old, new) { - if self.const_ids.get(&self.consts[o as usize]) == Some(&o) { - let prev = self.consts[o as usize].clone(); - self.const_ids.remove(&prev); - } self.consts[o as usize] = self.consts[n as usize].clone(); } } @@ -359,6 +376,16 @@ impl Module { g } + /// Notes what instruction `v` is for (see [`Tag`]); only when modules + /// are counted. + pub fn tag(&mut self, v: V, tag: Tag) { + if let V::Inst(i) = v + && census::enabled() + { + self.tags.insert(i, tag); + } + } + pub fn new_block(&mut self) -> usize { self.blocks.push(Block::default()); self.blocks.len() - 1 @@ -490,38 +517,12 @@ impl Module { self.named.push((name.into(), nodes)); } - /// Blocks reachable from entry (index 0) and their reverse postorder. - fn reachable(&self) -> (Vec, Vec) { - 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(); - (seen, post) - } - - /// Which instructions are written: every body instruction in reachable - /// blocks, the branch conditions, and whatever they read, transitively - /// (a phi nothing reads, or an incoming edge from an unreachable block, + /// 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. - fn live(&self, reachable: &[bool]) -> Vec { + fn live(&self) -> Vec { let mut live = vec![false; self.insts.len()]; let mut work: Vec = Vec::new(); let mark = |live: &mut [bool], work: &mut Vec, v: V| { @@ -532,10 +533,7 @@ impl Module { work.push(i); } }; - for (b_idx, b) in self.blocks.iter().enumerate() { - if !reachable[b_idx] { - continue; - } + for b in &self.blocks { for &i in &b.body { mark(&mut live, &mut work, V::Inst(i)); } @@ -544,16 +542,9 @@ impl Module { } } while let Some(i) = work.pop() { - match &self.insts[i as usize].op { - Op::Phi(inc) => { - for &(v, pred) in inc { - if reachable[pred] { - mark(&mut live, &mut work, v); - } - } - } - op => for_each_operand(op, |v| mark(&mut live, &mut work, v)), - } + for_each_operand(&self.insts[i as usize].op, |v| { + mark(&mut live, &mut work, v) + }); } live } @@ -591,6 +582,7 @@ impl Module { match t { TypeDef::Void => w.record(2, &[]), TypeDef::Float => w.record(3, &[]), + TypeDef::Double => w.record(4, &[]), TypeDef::Int(b) => w.record(7, &[u64::from(*b)]), TypeDef::Ptr(p, space) => w.record(8, &[u64::from(p.0), u64::from(*space)]), TypeDef::Array(n, e) => w.record(11, &[u64::from(*n), u64::from(e.0)]), @@ -690,13 +682,33 @@ 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 (seen, post) = self.reachable(); - // Phis nothing reads (and operands from unreachable edges) are left out. - let live = self.live(&seen); 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; @@ -710,19 +722,15 @@ impl Module { preds[s].push(b); } } - let mut fold: Vec> = vec![None; self.blocks.len()]; - let mut folded_edges: HashSet<(usize, usize)> = HashSet::new(); + 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.is_empty() && blk.body.is_empty(), &preds[b][..], - ) && fold[*p].is_none() - && fold[h].is_none() - && pos[h] < pos[b] + ) && pos[h] < pos[b] && !succs(*p).contains(&h) - && folded_edges.insert((*p, h)) { fold[b] = Some((*p, h)); } @@ -847,9 +855,6 @@ impl Module { r.clear(); r.push(u64::from(inst.ty.0)); for &(v, b) in incoming { - if !seen[b] { - continue; - } r.push(signed(i64::from(inst_id) - i64::from(abs(v)))); r.push(from(b)); } @@ -1158,8 +1163,7 @@ mod tests { fn worklist_liveness_matches_passes() { for (regs, stages, read) in [(1, 0, 1), (1, 1, 1), (4, 3, 1), (8, 17, 3), (16, 40, 16)] { let m = synthetic(regs, stages, read); - let (reach, _) = m.reachable(); - let live = m.live(&reach); + let live = m.live(); assert_eq!(live, live_by_passes(&m), "{regs} regs x {stages} stages"); } } @@ -1186,25 +1190,12 @@ mod tests { V::Inst(i) => i as usize, _ => unreachable!(), }; - let (reach, _) = m.reachable(); - let live = m.live(&reach); + let live = m.live(); assert!(live[ids(read)] && live[ids(sum)]); assert!(!live[ids(unread)] && !live[ids(cyc_a)] && !live[ids(cyc_b)]); assert_eq!(live, live_by_passes(&m)); } - #[test] - fn replace_const_evicts_old_cache_key() { - let mut m = Module::default(); - let c42 = m.i32(42); - let c99 = m.i32(99); - m.replace_const(c42, c99); - let fresh_42 = m.i32(42); - assert_ne!(fresh_42, c42); - assert_eq!(m.int_value(c42), Some(99)); - assert_eq!(m.int_value(fresh_42), Some(42)); - } - #[test] fn successors_of_each_terminator() { assert!(successors(None).is_empty()); diff --git a/crates/victory-shader/src/emit/bitcode/census.rs b/crates/victory-shader/src/emit/bitcode/census.rs new file mode 100644 index 0000000..03eeccf --- /dev/null +++ b/crates/victory-shader/src/emit/bitcode/census.rs @@ -0,0 +1,174 @@ +//! Counts of a module's instructions by kind (a diagnostic): what a +//! translated program costs before the driver's compiler sees it. +//! +//! `VICTORY_SHADER_CENSUS` (any value) turns the counting on; the counts of +//! the module a thread wrote last are read with [`take`]. The `translate` +//! command writes them as a table (see `apps/victory/src/translate.rs`). + +use super::{Cast, Module, Op, Tag, Term, V}; +use std::cell::RefCell; + +/// The kinds, in the order of [`Census::counts`]. +pub const KINDS: [&str; 26] = [ + "total", + "arith", + "math_call", + "bitcast", + "cast", + "select", + "guard_select", + "phi", + "extract", + "buffer_load", + "cbuffer_load", + "texture_read", + "lds_load", + "buffer_store", + "lds_store", + "atomic", + "handle", + "annotate", + "dimensions", + "barrier", + "wave_op", + "io_other", + "gep", + "clamp", + "loop_counter", + "blocks", +]; + +/// Instruction counts of one written module, by [`KINDS`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Census { + pub counts: [u32; KINDS.len()], +} + +thread_local! { + /// The modules this thread wrote since the last [`take`]: the length and + /// a hash of each one's bitcode, with its counts (a program may be + /// emitted in several forms before one is kept). + static WRITTEN: RefCell> = const { RefCell::new(Vec::new()) }; +} + +fn fnv(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| { + (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) + }) +} + +/// Whether modules are counted (`VICTORY_SHADER_CENSUS` set). +pub fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SHADER_CENSUS").is_some()) +} + +/// The counts of the module whose bitcode the container `dxil` holds, if +/// this thread wrote it since the last call (which forgets the others). +pub fn take(dxil: &[u8]) -> Option { + let written = WRITTEN.with(|l| std::mem::take(&mut *l.borrow_mut())); + let at = dxil.windows(4).position(|w| w == b"BC\xC0\xDE")?; + written + .into_iter() + .rev() + .find(|(len, hash, _)| dxil.get(at..at + len).is_some_and(|b| fnv(b) == *hash)) + .map(|w| w.2) +} + +/// Counts `m`, whose written form is `bitcode`, and keeps the result for +/// [`take`]. +pub(crate) fn note(m: &Module, bitcode: &[u8]) { + if !enabled() { + return; + } + let c = m.census(); + WRITTEN.with(|l| l.borrow_mut().push((bitcode.len(), fnv(bitcode), c))); +} + +fn kind(name: &str) -> usize { + let n = name.strip_prefix("dx.op.").unwrap_or(name); + let n = n.split('.').next().unwrap_or(n); + let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind"); + match n { + "unary" | "binary" | "tertiary" | "unaryBits" | "legacyF16ToF32" | "legacyF32ToF16" + | "isSpecialFloat" | "dot2" | "dot3" | "dot4" | "quaternary" => k("math_call"), + "bufferLoad" | "rawBufferLoad" => k("buffer_load"), + "cbufferLoadLegacy" | "cbufferLoad" => k("cbuffer_load"), + "bufferStore" | "rawBufferStore" | "textureStore" => k("buffer_store"), + "atomicBinOp" | "atomicCompareExchange" => k("atomic"), + "createHandle" | "createHandleFromBinding" | "createHandleFromHeap" => k("handle"), + "annotateHandle" => k("annotate"), + "getDimensions" => k("dimensions"), + "barrier" => k("barrier"), + _ if n.starts_with("wave") || n.starts_with("quad") => k("wave_op"), + _ if n.starts_with("textureLoad") + || n.starts_with("sample") + || n.starts_with("textureGather") + || n.starts_with("calculateLOD") => + { + k("texture_read") + } + _ => k("io_other"), + } +} + +impl Module { + /// The instructions [`Module::write`] writes, by kind. + pub(crate) fn census(&self) -> Census { + let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind"); + let call_kind: Vec = self.funcs.iter().map(|f| kind(&f.name)).collect(); + let live = self.live(); + // The blocks `write` lays out: those reached from the entry. + let mut seen = vec![false; self.blocks.len()]; + let mut stack = vec![0usize]; + if !self.blocks.is_empty() { + seen[0] = true; + } + while let Some(b) = stack.pop() { + for &s in super::successors(self.blocks[b].term).iter() { + if !seen[s] { + seen[s] = true; + stack.push(s); + } + } + } + let mut c = Census::default(); + for (b, blk) in self.blocks.iter().enumerate() { + if !seen[b] { + continue; + } + c.counts[k("blocks")] += 1; + let _: Option = blk.term; + for &i in blk + .phis + .iter() + .filter(|&&i| live[i as usize]) + .chain(&blk.body) + { + c.counts[0] += 1; + let at = match &self.insts[i as usize].op { + Op::Bin(..) | Op::Cmp(..) => k("arith"), + Op::Cast(Cast::Bitcast, _) => k("bitcast"), + Op::Cast(..) => k("cast"), + Op::Select(..) => k("select"), + Op::Extract(..) => k("extract"), + Op::Phi(_) => k("phi"), + Op::Gep(..) => k("gep"), + Op::Load(_) => k("lds_load"), + Op::Store(..) => k("lds_store"), + Op::AtomicRmw(..) | Op::CmpXchg(..) => k("atomic"), + Op::Call(f, _) => call_kind[*f as usize], + }; + c.counts[at] += 1; + match self.tags.get(&i) { + Some(Tag::Guard) => c.counts[k("guard_select")] += 1, + Some(Tag::Clamp) => c.counts[k("clamp")] += 1, + Some(Tag::Counter) => c.counts[k("loop_counter")] += 1, + None => {} + } + let _ = V::Inst(i); + } + } + c + } +} diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs new file mode 100644 index 0000000..13551c3 --- /dev/null +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -0,0 +1,2136 @@ +//! Clean-up of a finished module before it is written: the lowering emits +//! one instruction after another as the console code names them, and +//! nothing stands between it and the driver's compiler. Every pass here is +//! exact: the module computes the same values and has the same effects for +//! every input. +//! +//! - [`DEAD`]: instructions without an effect whose result nothing reads +//! are left out (the lowering computes every dword of every register a +//! console instruction writes; a guarded write reads the register's old +//! value whether anything reads the new one or not). +//! - [`FOLD`]: integer arithmetic on constants is done here, and identities +//! (`x + 0`, `x & -1`, a select between a value and itself, a cast there +//! and back, a join of one value) give their operand. Float arithmetic is +//! left alone: `x + 0.0` and `x * 1.0` are not `x` for every `x`. +//! - [`REUSE`]: an instruction without an effect whose operands are those +//! of an earlier one that every path to it has run gives that one's +//! result (a descriptor handle made again in each block, an index clamped +//! again, a register read as a float again). +//! - [`FACTS`]: in the blocks only one side of a branch leads to, the +//! branch's condition is that side's constant, and so is what the +//! condition was made of (both terms of an `and` that held, the opposite +//! comparison). The lowering branches on a lane's condition and then +//! guards each instruction behind the branch with the same condition. +//! - [`LOADS`]: within a block, a read of the same place as an earlier read +//! gives that one's result while no store, atomic, barrier or other call +//! with an effect stands between them (another thread's unsynchronised +//! store may fall between any two reads or before both: the title's code +//! cannot tell which). +//! +//! Which passes run is `emit::shader_opt()` (`VICTORY_SHADER_OPT`), part of +//! the translation and so of the shader cache's key. + +use std::collections::HashMap; + +use super::{ + Attr, Bin, Cast, Const, Func, MdDef, Module, Op, Term, Ty, TypeDef, V, for_each_operand, pred, + successors, +}; + +/// Dead-code elimination. +pub const DEAD: u32 = 1; +/// Constants folded, identities removed. +pub const FOLD: u32 = 2; +/// One instruction for one value. +pub const REUSE: u32 = 4; +/// What a branch taken says about its condition. +pub const FACTS: u32 = 8; +/// One read for one place within a block, while nothing is stored. +pub const LOADS: u32 = 16; +/// Not a pass over the module: the lowering of a first-lane read in a +/// wave64 program run as two host waves skips the exchange that asks which +/// half has a lane where every lane is in EXEC (`lower.rs`, +/// `v_readfirstlane_b32`). +pub const FIRST: u32 = 32; +/// The passes over the module. +pub const MODULE: u32 = DEAD | FOLD | REUSE | FACTS | LOADS; +/// Every pass. +pub const ALL: u32 = MODULE | FIRST; + +/// What the instructions a module writes use, of the features a shader +/// declares by flag (the validator's "flags must match usage"). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct Usage { + /// A wave or quad operation. + pub wave_ops: bool, + /// A 64-bit integer, as a result or an operand. + pub int64: bool, + /// A typed load of several components from a UAV. + pub typed_uav_loads: bool, + /// A handle from the view heap. + pub heap_views: bool, + /// A handle from the sampler heap. + pub heap_samplers: bool, + /// A 64-bit atomic. + pub atomic64: bool, +} + +/// What makes two instructions without an effect the same value. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Key { + Bin(u8, V, V), + Cast(u8, Ty, V), + Cmp(u8, V, V), + Select(V, V, V), + Extract(V, u32), + Call(u32, Vec), + Gep(Ty, V, Vec), + Load(V), +} + +/// The blocks reached from the entry, each after the blocks that dominate +/// it, and each block's children in the dominator tree. +struct Tree { + order: Vec, + children: Vec>, + /// Per block: the reached blocks that branch to it, once per edge. + preds: Vec>, +} + +/// The comparison that holds exactly when `p` does not (floats 0-15, +/// integers 32-41). +fn opposite(p: u8) -> u8 { + match p { + 0..=15 => 15 - p, + pred::EQ => pred::NE, + pred::NE => pred::EQ, + pred::IUGT => pred::IULE, + pred::IULE => pred::IUGT, + pred::IUGE => pred::IULT, + pred::IULT => pred::IUGE, + pred::SGT => pred::SLE, + pred::SLE => pred::SGT, + pred::SGE => pred::SLT, + _ => pred::SGE, + } +} + +/// What holds in the block being walked: values that are a known bit there, +/// and comparisons (by their operands) with a known outcome. +#[derive(Default)] +struct Facts { + bits: HashMap, + compares: HashMap<(u8, V, V), bool>, +} + +/// The facts a block added, to forget when its part of the tree is done. +#[derive(Default)] +struct Learned { + bits: Vec, + compares: Vec<(u8, V, V)>, +} + +fn mask(bits: u32) -> u64 { + if bits >= 64 { !0 } else { (1 << bits) - 1 } +} + +/// `x` of `bits` bits as a signed number. +fn signed(bits: u32, x: u64) -> i64 { + if bits < 64 && x >> (bits - 1) & 1 != 0 { + (x | !mask(bits)) as i64 + } else { + x as i64 + } +} + +/// What `v` stands for after the replacements so far. +fn resolve(repl: &[Option], mut v: V) -> V { + while let V::Inst(i) = v { + match repl[i as usize] { + Some(r) => v = r, + None => break, + } + } + v +} + +/// Replaces every value `op` reads by `f` of it. +fn map_operands(op: &mut Op, mut f: impl FnMut(V) -> V) { + match op { + Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => { + *a = f(*a); + *b = f(*b); + } + Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => *v = f(*v), + Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { + *a = f(*a); + *b = f(*b); + *c = f(*c); + } + Op::Call(_, args) => args.iter_mut().for_each(|a| *a = f(*a)), + Op::Phi(inc) => inc.iter_mut().for_each(|x| x.0 = f(x.0)), + Op::Gep(_, p, idx) => { + *p = f(*p); + idx.iter_mut().for_each(|i| *i = f(*i)); + } + } +} + +/// What a call does besides returning its result. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Effect { + /// Nothing, and the result depends on the arguments alone for the whole + /// run of the shader (arithmetic, handles, inputs, constant buffers, + /// resource sizes). + Pure, + /// Nothing, but the result depends on memory a store may change + /// (buffer and texture reads). + Reads, + /// Nothing, but the result depends on which lanes run the instruction + /// (wave and quad operations). + Lanes, + /// Stores, atomics, barriers, outputs, discards: always kept. + Writes, +} + +pub(super) fn effect(f: &Func) -> Effect { + let name = f.name.strip_prefix("dx.op.").unwrap_or(&f.name); + match f.attr { + Some(Attr::ReadNone) => Effect::Pure, + // A shader cannot write a constant buffer or resize a resource. + Some(Attr::ReadOnly) + if name.starts_with("cbufferLoadLegacy") || name.starts_with("getDimensions") => + { + Effect::Pure + } + Some(Attr::ReadOnly) if name.starts_with("wave") => Effect::Lanes, + Some(Attr::ReadOnly) => Effect::Reads, + // Declared with the attribute of calls that have effects, and have + // none: they read the other lanes' values. + _ if name.starts_with("wave") || name.starts_with("quad") => Effect::Lanes, + _ => Effect::Writes, + } +} + +impl Module { + /// Runs the clean-up passes named in `passes` ([`ALL`]: every one). + pub(crate) fn optimise(&mut self, passes: u32) { + if passes & (FOLD | REUSE | FACTS | LOADS) != 0 { + // Values merged in one round can make two joins the same in + // the next (a loop's registers that only go round), and a + // branch that goes one way leaves blocks with one way in. + for _ in 0..4 { + let mut changed = self.merge(passes); + if passes & FOLD != 0 { + changed |= self.prune(); + } + if !changed { + break; + } + } + } + if passes & DEAD != 0 { + self.drop_dead(); + } + } + + /// Per function: what a call of it does. + pub(super) fn effects(&self) -> Vec { + self.funcs.iter().map(effect).collect() + } + + /// The blocks reached from the entry. + pub(super) fn reached(&self) -> Vec { + let mut seen = vec![false; self.blocks.len()]; + if self.blocks.is_empty() { + return seen; + } + let mut stack = vec![0usize]; + seen[0] = true; + while let Some(b) = stack.pop() { + for &s in successors(self.blocks[b].term).iter() { + if !seen[s] { + seen[s] = true; + stack.push(s); + } + } + } + seen + } + + fn dominator_tree(&self) -> Tree { + let n = self.blocks.len(); + let succs = |b: usize| successors(self.blocks[b].term); + // Reverse postorder, as `write` lays the blocks out. + let mut seen = vec![false; n]; + 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 order = post; + let mut number = vec![usize::MAX; n]; + for (k, &b) in order.iter().enumerate() { + number[b] = k; + } + let mut preds = vec![Vec::new(); n]; + for &b in &order { + for &s in succs(b).iter() { + preds[s].push(b); + } + } + // Immediate dominators (Cooper, Harvey and Kennedy's iteration). + let mut idom = vec![usize::MAX; n]; + idom[0] = 0; + let mut changed = true; + while changed { + changed = false; + for &b in &order[1..] { + let mut new = usize::MAX; + for &p in &preds[b] { + if idom[p] == usize::MAX { + continue; + } + if new == usize::MAX { + new = p; + continue; + } + let (mut x, mut y) = (p, new); + while x != y { + while number[x] > number[y] { + x = idom[x]; + } + while number[y] > number[x] { + y = idom[y]; + } + } + new = x; + } + if idom[b] != new { + idom[b] = new; + changed = true; + } + } + } + let mut children = vec![Vec::new(); n]; + for &b in &order[1..] { + children[idom[b]].push(b); + } + Tree { + order, + children, + preds, + } + } + + /// Notes that `v` (an i1) is `holds` in the block being walked, and what + /// follows from it for the values `v` was made of. + fn learn(&self, v: V, holds: bool, facts: &mut Facts, learned: &mut Learned, depth: u32) { + let V::Inst(i) = v else { return }; + if facts.bits.contains_key(&v) { + return; + } + facts.bits.insert(v, holds); + learned.bits.push(v); + if depth == 0 { + return; + } + match self.insts[i as usize].op { + // Both terms of an `and` that holds hold; neither of an `or` + // that does not. + Op::Bin(Bin::And, a, b) if holds => { + self.learn(a, true, facts, learned, depth - 1); + self.learn(b, true, facts, learned, depth - 1); + } + Op::Bin(Bin::Or, a, b) if !holds => { + self.learn(a, false, facts, learned, depth - 1); + self.learn(b, false, facts, learned, depth - 1); + } + Op::Bin(Bin::Xor, a, b) => { + let (x, k) = match (self.int_k(a), self.int_k(b)) { + (None, Some((1, k))) => (a, k), + (Some((1, k)), None) => (b, k), + _ => return, + }; + self.learn(x, holds != (k != 0), facts, learned, depth - 1); + } + // The opposite comparison of the same operands. + Op::Cmp(p, a, b) => { + let key = (opposite(p), a, b); + if let std::collections::hash_map::Entry::Vacant(e) = facts.compares.entry(key) { + e.insert(!holds); + learned.compares.push(key); + } + } + _ => {} + } + } + + fn int_bits(&self, ty: Ty) -> Option { + match self.types[ty.0 as usize] { + TypeDef::Int(bits) => Some(bits), + _ => None, + } + } + + /// An integer constant's width and value (the bits of that width). + fn int_k(&self, v: V) -> Option<(u32, u64)> { + let V::Const(i) = v else { return None }; + let (ty, Const::Int(x)) = &self.consts[i as usize] else { + return None; + }; + let bits = self.int_bits(*ty)?; + Some((bits, *x as u64 & mask(bits))) + } + + /// The constant `x` of the integer type `ty`, kept sign-extended as + /// [`Module::i32`] and [`Module::bool`] keep theirs. + fn k(&mut self, ty: Ty, bits: u32, x: u64) -> V { + self.int_const(ty, signed(bits, x & mask(bits))) + } + + /// The value instruction `i` is known to have without it, if any: a + /// constant or an earlier value. May instead give `i` simpler operands + /// (`changed` says so). + fn simplify(&mut self, i: u32, changed: &mut bool) -> Option { + let ty = self.insts[i as usize].ty; + match self.insts[i as usize].op { + Op::Bin(op, a, b) => { + // Floats: `x + 0.0`, `x * 1.0` and the like are not `x` for + // every `x` (a negative zero, a signalling NaN). + let bits = self.int_bits(ty)?; + let (ka, kb) = (self.int_k(a).map(|k| k.1), self.int_k(b).map(|k| k.1)); + let all = mask(bits); + if let (Some(x), Some(y)) = (ka, kb) { + // A shift by the width or more and a division by zero + // have no defined result: left as they are. + let amount = u32::try_from(y).ok().filter(|&y| y < bits); + let r = match op { + Bin::Add => x.wrapping_add(y), + Bin::Sub => x.wrapping_sub(y), + Bin::Mul => x.wrapping_mul(y), + Bin::And => x & y, + Bin::Or => x | y, + Bin::Xor => x ^ y, + Bin::Shl => x << amount?, + Bin::LShr => x >> amount?, + Bin::AShr => (signed(bits, x) >> amount?) as u64, + Bin::UDiv if y != 0 => x / y, + Bin::URem if y != 0 => x % y, + _ => return None, + }; + return Some(self.k(ty, bits, r)); + } + match (op, ka, kb) { + ( + Bin::Add | Bin::Sub | Bin::Or | Bin::Xor | Bin::Shl | Bin::LShr | Bin::AShr, + _, + Some(0), + ) => Some(a), + (Bin::Add | Bin::Or | Bin::Xor, Some(0), _) => Some(b), + (Bin::Mul | Bin::UDiv, _, Some(1)) => Some(a), + (Bin::Mul, Some(1), _) => Some(b), + (Bin::Mul | Bin::And, _, Some(0)) => Some(b), + (Bin::Mul | Bin::And, Some(0), _) => Some(a), + (Bin::And, _, Some(m)) if m == all => Some(a), + (Bin::And, Some(m), _) if m == all => Some(b), + (Bin::Or, _, Some(m)) if m == all => Some(b), + (Bin::Or, Some(m), _) if m == all => Some(a), + (Bin::And | Bin::Or, _, _) if a == b => Some(a), + _ => None, + } + } + Op::Cmp(p, a, b) if p <= pred::TRUE => { + // Two float constants compare one way (`v_mul_legacy` asks + // whether its constant factor is zero). + let (V::Const(x), V::Const(y)) = (a, b) else { + return None; + }; + let (Const::Float(x), Const::Float(y)) = + (&self.consts[x as usize].1, &self.consts[y as usize].1) + else { + return None; + }; + let (x, y) = (f32::from_bits(*x), f32::from_bits(*y)); + let unordered = x.is_nan() || y.is_nan(); + // Bits 0-2 of a predicate: equal, greater, less; bit 3: + // or unordered. + let holds = if unordered { + p & 8 != 0 + } else { + (p & 1 != 0 && x == y) || (p & 2 != 0 && x > y) || (p & 4 != 0 && x < y) + }; + Some(self.bool(holds)) + } + Op::Cmp(p, a, b) => { + if !(pred::EQ..=pred::SLE).contains(&p) { + return None; + } + let holds = |x: u64, y: u64, bits: u32| { + let (sx, sy) = (signed(bits, x), signed(bits, y)); + match p { + pred::EQ => x == y, + pred::NE => x != y, + pred::IUGT => x > y, + pred::IUGE => x >= y, + pred::IULT => x < y, + pred::IULE => x <= y, + pred::SGT => sx > sy, + pred::SGE => sx >= sy, + pred::SLT => sx < sy, + _ => sx <= sy, + } + }; + if let (Some((bits, x)), Some((_, y))) = (self.int_k(a), self.int_k(b)) { + return Some(self.bool(holds(x, y, bits))); + } + if a == b { + return Some(self.bool(holds(0, 0, 32))); + } + // A bit widened and tested again is the bit. + if p == pred::NE + && self.int_k(b).is_some_and(|k| k.1 == 0) + && let V::Inst(z) = a + && let Op::Cast(Cast::ZExt, x) = self.insts[z as usize].op + && self.type_of(x) == ty + { + return Some(x); + } + None + } + Op::Select(c, mut t, mut f) => { + if let Some((_, c)) = self.int_k(c) { + return Some(if c != 0 { t } else { f }); + } + // Under the same condition an inner select is one of its + // operands (two guarded writes of one register in a row). + let mut inner = false; + while let V::Inst(x) = t + && let Op::Select(c2, t2, _) = self.insts[x as usize].op + && c2 == c + { + (t, inner) = (t2, true); + } + while let V::Inst(x) = f + && let Op::Select(c2, _, f2) = self.insts[x as usize].op + && c2 == c + { + (f, inner) = (f2, true); + } + if t == f { + return Some(t); + } + if self.int_bits(ty) == Some(1) + && self.int_k(t).is_some_and(|k| k.1 == 1) + && self.int_k(f).is_some_and(|k| k.1 == 0) + { + return Some(c); + } + if inner { + self.insts[i as usize].op = Op::Select(c, t, f); + *changed = true; + } + None + } + Op::Cast(op, x) => { + let from = self.type_of(x); + let through = match x { + V::Inst(y) => match self.insts[y as usize].op { + Op::Cast(op2, z) => Some((op2, z)), + _ => None, + }, + _ => None, + }; + match op { + Cast::Bitcast => { + if from == ty { + return Some(x); + } + // There and back: the bits are the same. + if let Some((Cast::Bitcast, z)) = through + && self.type_of(z) == ty + { + return Some(z); + } + let V::Const(c) = x else { return None }; + let to_float = matches!(self.types[ty.0 as usize], TypeDef::Float); + match self.consts[c as usize].1 { + Const::Int(bits) if to_float && self.int_bits(from) == Some(32) => { + Some(self.f32(bits as u32)) + } + Const::Float(bits) if self.int_bits(ty) == Some(32) => { + Some(self.int_const(ty, i64::from(bits as i32))) + } + _ => None, + } + } + Cast::ZExt | Cast::SExt | Cast::Trunc => { + let to = self.int_bits(ty)?; + if let Some((bits, k)) = self.int_k(x) { + let k = if op == Cast::SExt { + signed(bits, k) as u64 + } else { + k + }; + return Some(self.k(ty, to, k)); + } + // Widened and narrowed again. + if op == Cast::Trunc + && let Some((Cast::ZExt | Cast::SExt, z)) = through + && self.type_of(z) == ty + { + return Some(z); + } + None + } + _ => None, + } + } + _ => None, + } + } + + /// What kind of instruction `i` is for merging. + fn class(&self, effects: &[Effect], i: u32) -> Effect { + match &self.insts[i as usize].op { + Op::Bin(..) + | Op::Cast(..) + | Op::Cmp(..) + | Op::Select(..) + | Op::Extract(..) + | Op::Gep(..) => Effect::Pure, + Op::Load(p) => { + // A constant table reads the same whatever is stored. + let base = match *p { + V::Inst(g) => match &self.insts[g as usize].op { + Op::Gep(_, base, _) => *base, + _ => *p, + }, + _ => *p, + }; + match base { + V::Global(g) if self.globals[g as usize].init.is_some() => Effect::Pure, + _ => Effect::Reads, + } + } + Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => Effect::Writes, + Op::Phi(_) => Effect::Lanes, + Op::Call(f, _) => effects[*f as usize], + } + } + + fn key(&self, i: u32) -> Option { + let inst = &self.insts[i as usize]; + Some(match &inst.op { + Op::Bin(op, a, b) => { + // Integer sums, products and bit operations whichever way + // round; float ones as written (which NaN an operation of + // two NaNs gives is the hardware's choice by operand). + let commutes = matches!(op, Bin::Add | Bin::Mul | Bin::And | Bin::Or | Bin::Xor) + && self.int_bits(inst.ty).is_some(); + let (a, b) = if commutes && b < a { + (*b, *a) + } else { + (*a, *b) + }; + Key::Bin(*op as u8, a, b) + } + Op::Cast(op, v) => Key::Cast(*op as u8, inst.ty, *v), + Op::Cmp(p, a, b) => Key::Cmp(*p, *a, *b), + Op::Select(c, t, f) => Key::Select(*c, *t, *f), + Op::Extract(a, n) => Key::Extract(*a, *n), + Op::Call(f, args) => Key::Call(*f, args.clone()), + Op::Gep(ty, p, idx) => Key::Gep(*ty, *p, idx.clone()), + Op::Load(p) => Key::Load(*p), + _ => return None, + }) + } + + /// [`FOLD`], [`REUSE`], [`FACTS`] and [`LOADS`]: one walk over the + /// dominator tree. Returns whether anything changed. + fn merge(&mut self, passes: u32) -> bool { + if self.blocks.is_empty() { + return false; + } + let effects = self.effects(); + let tree = self.dominator_tree(); + let mut repl: Vec> = vec![None; self.insts.len()]; + let mut changed = false; + // Joins of one value: until none is left (one gone can leave + // another with one value). + if passes & FOLD != 0 { + let mut again = true; + while again { + again = false; + for &b in &tree.order { + for &p in &self.blocks[b].phis { + if repl[p as usize].is_some() { + continue; + } + let Op::Phi(incoming) = &self.insts[p as usize].op else { + continue; + }; + let mut one = None; + let mut same = true; + for &(v, _) in incoming { + let v = resolve(&repl, v); + if v == V::Inst(p) { + continue; + } + match one { + None => one = Some(v), + Some(o) if o == v => {} + Some(_) => same = false, + } + } + if let (true, Some(v)) = (same, one) { + repl[p as usize] = Some(v); + again = true; + changed = true; + } + } + } + } + } + // The values every path to the block being walked has computed + // (those of the blocks above it in the tree, and its own so far). + let mut known: HashMap = HashMap::new(); + // The reads of the block being walked since its last store. + let mut read: HashMap = HashMap::new(); + let mut facts = Facts::default(); + let (yes, no) = (self.bool(true), self.bool(false)); + enum Step { + Enter(usize), + Leave(Vec, Learned), + } + let mut steps = vec![Step::Enter(0)]; + while let Some(step) = steps.pop() { + let b = match step { + Step::Enter(b) => b, + Step::Leave(keys, learned) => { + for k in keys { + known.remove(&k); + } + for v in learned.bits { + facts.bits.remove(&v); + } + for k in learned.compares { + facts.compares.remove(&k); + } + continue; + } + }; + let mut added = Vec::new(); + // Reached from one block alone, by one side of its branch: the + // condition is that side's, here and in every block below. + let mut learned = Learned::default(); + if passes & FACTS != 0 + && let [p] = tree.preds[b][..] + && let Some(Term::CondBr(c, t, f)) = self.blocks[p].term + && t != f + { + self.learn(resolve(&repl, c), b == t, &mut facts, &mut learned, 8); + } + let known_bit = |facts: &Facts, v: V| match facts.bits.get(&v) { + Some(true) => yes, + Some(false) => no, + None => v, + }; + read.clear(); + // Two joins of the same values from the same blocks are one. + if passes & REUSE != 0 && self.blocks[b].phis.len() > 1 { + let mut joins: HashMap, V> = HashMap::new(); + for &p in &self.blocks[b].phis { + if repl[p as usize].is_some() { + continue; + } + let ty = self.insts[p as usize].ty; + let Op::Phi(incoming) = &self.insts[p as usize].op else { + continue; + }; + let mut key: Vec<(usize, V)> = incoming + .iter() + .map(|&(v, from)| (from, resolve(&repl, v))) + .collect(); + key.sort(); + // The type too: an undefined value of one type is not + // that of another. + key.push((ty.0 as usize, V::Global(u32::MAX))); + match joins.get(&key) { + Some(&first) => { + repl[p as usize] = Some(first); + changed = true; + } + None => { + joins.insert(key, V::Inst(p)); + } + } + } + } + let body = std::mem::take(&mut self.blocks[b].body); + let mut kept = Vec::with_capacity(body.len()); + for i in body { + map_operands(&mut self.insts[i as usize].op, |v| { + let v = resolve(&repl, v); + let bit = known_bit(&facts, v); + changed |= bit != v; + bit + }); + if let Op::Cmp(p, x, y) = self.insts[i as usize].op + && let Some(&holds) = facts.compares.get(&(p, x, y)) + { + repl[i as usize] = Some(if holds { yes } else { no }); + changed = true; + continue; + } + if passes & FOLD != 0 + && let Some(v) = self.simplify(i, &mut changed) + { + repl[i as usize] = Some(v); + changed = true; + continue; + } + let class = self.class(&effects, i); + if passes & REUSE != 0 + && class == Effect::Pure + && let Some(key) = self.key(i) + { + if let Some(&first) = known.get(&key) { + repl[i as usize] = Some(first); + changed = true; + continue; + } + known.insert(key.clone(), V::Inst(i)); + added.push(key); + } + // Reads of memory, and wave operations (the same lanes run + // the whole block): the block's own earlier one. + if passes & LOADS != 0 + && matches!(class, Effect::Reads | Effect::Lanes) + && let Some(key) = self.key(i) + { + if let Some(&first) = read.get(&key) { + repl[i as usize] = Some(first); + changed = true; + continue; + } + read.insert(key, V::Inst(i)); + } + if class == Effect::Writes { + read.clear(); + } + kept.push(i); + } + self.blocks[b].body = kept; + if let Some(Term::CondBr(c, t, f)) = self.blocks[b].term { + let c = known_bit(&facts, resolve(&repl, c)); + self.blocks[b].term = Some(Term::CondBr(c, t, f)); + } + steps.push(Step::Leave(added, learned)); + for &c in tree.children[b].iter().rev() { + steps.push(Step::Enter(c)); + } + } + if !changed { + return false; + } + // Everything that read a replaced value reads its replacement + // (joins read values from blocks walked after them). + for blk in &mut self.blocks { + blk.phis.retain(|&p| repl[p as usize].is_none()); + if let Some(Term::CondBr(c, t, f)) = blk.term { + blk.term = Some(Term::CondBr(resolve(&repl, c), t, f)); + } + } + let (blocks, insts) = (&self.blocks, &mut self.insts); + for blk in blocks { + for &i in blk.phis.iter().chain(&blk.body) { + map_operands(&mut insts[i as usize].op, |v| resolve(&repl, v)); + } + } + true + } + + /// [`FOLD`]: a branch on a constant goes one way. The side not taken + /// loses the branching block's values at its joins, and so do the joins + /// of blocks that nothing reaches any more. Returns whether a branch + /// changed. + fn prune(&mut self) -> bool { + let mut changed = false; + for b in 0..self.blocks.len() { + let Some(Term::CondBr(c, t, f)) = self.blocks[b].term else { + continue; + }; + // Both sides one block: two edges into it, left as they are. + if t == f { + continue; + } + let Some((_, k)) = self.int_k(c) else { + continue; + }; + let (taken, not) = if k != 0 { (t, f) } else { (f, t) }; + self.blocks[b].term = Some(Term::Br(taken)); + changed = true; + for n in 0..self.blocks[not].phis.len() { + let p = self.blocks[not].phis[n]; + if let Op::Phi(incoming) = &mut self.insts[p as usize].op { + incoming.retain(|&(_, from)| from != b); + } + } + } + if !changed { + return false; + } + let reached = self.reached(); + let (blocks, insts) = (&self.blocks, &mut self.insts); + for (_, blk) in blocks.iter().enumerate().filter(|(b, _)| reached[*b]) { + for &p in &blk.phis { + if let Op::Phi(incoming) = &mut insts[p as usize].op { + incoming.retain(|&(_, from)| reached[from]); + } + } + } + true + } + + /// Whether instruction `i` must stay whatever reads it. + fn has_effect(&self, effects: &[Effect], i: u32) -> bool { + match &self.insts[i as usize].op { + Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => true, + Op::Call(f, _) => effects[*f as usize] == Effect::Writes, + _ => false, + } + } + + /// [`DEAD`]: keeps the instructions with an effect, the branch + /// conditions, and what they read, transitively; the rest leave their + /// blocks. Blocks no branch reaches are emptied (they are not written). + fn drop_dead(&mut self) { + let effects = self.effects(); + let reached = self.reached(); + let mut live = vec![false; self.insts.len()]; + let mut work: Vec = Vec::new(); + let mark = |live: &mut [bool], work: &mut Vec, v: V| { + if let V::Inst(i) = v + && !live[i as usize] + { + live[i as usize] = true; + work.push(i); + } + }; + for (b, blk) in self.blocks.iter().enumerate() { + if !reached[b] { + continue; + } + for &i in &blk.body { + if self.has_effect(&effects, i) { + mark(&mut live, &mut work, V::Inst(i)); + } + } + if let Some(Term::CondBr(c, ..)) = blk.term { + mark(&mut live, &mut work, c); + } + } + while let Some(i) = work.pop() { + for_each_operand(&self.insts[i as usize].op, |v| { + mark(&mut live, &mut work, v) + }); + } + for (b, blk) in self.blocks.iter_mut().enumerate() { + if reached[b] { + blk.body.retain(|&i| live[i as usize]); + blk.phis.retain(|&i| live[i as usize]); + } else { + blk.body.clear(); + blk.phis.clear(); + } + } + self.drop_unused_functions(); + self.drop_unused_tables(); + } + + /// See [`Usage`]: over the blocks reached from the entry. + pub(crate) fn usage(&self) -> Usage { + let mut u = Usage::default(); + let reached = self.reached(); + let wide = |ty: Ty| self.types[ty.0 as usize] == TypeDef::Int(64); + // The first field of a handle's annotation: its kind, with the UAV + // bit; the second: the component type and count. + let annotation = |h: V| -> Option<(i64, i64)> { + let V::Inst(a) = h else { return None }; + let Op::Call(f, args) = &self.insts[a as usize].op else { + return None; + }; + if self.funcs[*f as usize].name != "dx.op.annotateHandle" { + return None; + } + let V::Const(props) = *args.get(2)? else { + return None; + }; + let Const::Aggregate(fields) = &self.consts[props as usize].1 else { + return None; + }; + match ( + &self.consts[fields[0] as usize].1, + &self.consts[fields[1] as usize].1, + ) { + (Const::Int(kind), Const::Int(components)) => Some((*kind, *components)), + _ => None, + } + }; + for (_, blk) in self.blocks.iter().enumerate().filter(|(b, _)| reached[*b]) { + for &i in blk.phis.iter().chain(&blk.body) { + 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(); + let name = name.strip_prefix("dx.op.").unwrap_or(name); + if name.starts_with("wave") || name.starts_with("quad") { + u.wave_ops = true; + } else if name == "createHandleFromHeap" { + match args.get(2).and_then(|&s| self.int_k(s)) { + Some((_, 0)) => u.heap_views = true, + _ => u.heap_samplers = true, + } + } else if name.starts_with("atomic") && name.ends_with(".i64") { + u.atomic64 = true; + } else if name.starts_with("textureLoad") || name.starts_with("bufferLoad") { + u.typed_uav_loads |= args.get(1).and_then(|&h| annotation(h)).is_none_or( + |(kind, components)| kind & 0x1000 != 0 && components >> 8 & 0xff > 1, + ); + } + } + } + u + } + + /// A constant table no remaining load reads leaves the module (the + /// validator refuses an internal declaration nothing uses). Shared + /// memory stays declared whether it is read or not. + fn drop_unused_tables(&mut self) { + let mut used: Vec = self.globals.iter().map(|g| g.init.is_none()).collect(); + if used.iter().all(|&u| u) { + return; + } + for blk in &self.blocks { + for &i in blk.phis.iter().chain(&blk.body) { + for_each_operand(&self.insts[i as usize].op, |v| { + if let V::Global(g) = v { + used[g as usize] = true; + } + }); + } + } + for md in &self.mds { + if let MdDef::Value(_, V::Global(g)) = md { + used[*g as usize] = true; + } + } + if used.iter().all(|&u| u) { + return; + } + let mut new = vec![u32::MAX; used.len()]; + for (next, (old, _)) in used.iter().enumerate().filter(|u| *u.1).enumerate() { + new[old] = next as u32; + } + let mut old = 0; + self.globals.retain(|_| { + old += 1; + used[old - 1] + }); + let renumber = |v: V| match v { + V::Global(g) if used[g as usize] => V::Global(new[g as usize]), + v => v, + }; + for inst in &mut self.insts { + map_operands(&mut inst.op, renumber); + } + for md in &mut self.mds { + if let MdDef::Value(_, v) = md { + *v = renumber(*v); + } + } + } + + /// Declarations no remaining call names leave the module (the validator + /// refuses an external function nothing uses); the others keep their + /// order, so `main` stays function 0. + fn drop_unused_functions(&mut self) { + let mut used: Vec = self.funcs.iter().map(|f| f.body).collect(); + for blk in &self.blocks { + for &i in blk.phis.iter().chain(&blk.body) { + if let Op::Call(f, _) = self.insts[i as usize].op { + used[f as usize] = true; + } + } + } + for md in &self.mds { + if let MdDef::Value(_, V::Func(f)) = md { + used[*f as usize] = true; + } + } + if used.iter().all(|&u| u) { + return; + } + let mut new = vec![u32::MAX; used.len()]; + for (next, (old, _)) in used.iter().enumerate().filter(|u| *u.1).enumerate() { + new[old] = next as u32; + } + let mut old = 0; + self.funcs.retain(|_| { + old += 1; + used[old - 1] + }); + self.func_ids = self + .funcs + .iter() + .enumerate() + .map(|(i, f)| (f.name.clone(), i as u32)) + .collect(); + // Instructions that left their block keep a stale number: nothing + // reads them again. + for inst in &mut self.insts { + if let Op::Call(f, _) = &mut inst.op + && used[*f as usize] + { + *f = new[*f as usize]; + } + } + for md in &mut self.mds { + if let MdDef::Value(_, V::Func(f)) = md { + *f = new[*f as usize]; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `main` with one block and a function of each kind of effect. + struct Kit { + m: Module, + b: usize, + pure: V, + reads: V, + writes: V, + } + + fn kit() -> Kit { + let mut m = Module::default(); + let i32t = m.int(32); + let void = m.void(); + let fty = m.func_ty(i32t, vec![i32t, i32t]); + m.ptr(fty); + let pure = m.function("dx.op.binary.i32", fty, Some(Attr::ReadNone), false); + let reads = m.function("dx.op.bufferLoad.i32", fty, Some(Attr::ReadOnly), false); + let writes = m.function("dx.op.bufferStore.i32", fty, Some(Attr::NoUnwind), false); + let main_ty = m.func_ty(void, vec![]); + m.ptr(main_ty); + m.function("main", main_ty, None, true); + let b = m.new_block(); + Kit { + m, + b, + pure, + reads, + writes, + } + } + + fn body(m: &Module, b: usize) -> usize { + m.blocks[b].body.len() + } + + #[test] + fn unread_results_without_effect_are_dropped() { + let Kit { + mut m, + b, + pure, + reads, + writes, + } = kit(); + let (one, two) = (m.i32(1), m.i32(2)); + let used = m.call(b, reads, vec![one, two]); + let dead = m.call(b, reads, vec![two, one]); + let chain = m.bin(b, Bin::Add, dead, one); + let _unread = m.call(b, pure, vec![chain, two]); + // A store's result is unread and stays, with what it reads. + let kept = m.bin(b, Bin::Add, used, two); + m.call(b, writes, vec![kept, one]); + m.terminate(b, Term::Ret); + m.optimise(DEAD); + assert_eq!(body(&m, b), 3, "the load, the add and the store"); + m.write(); + } + + #[test] + fn branch_conditions_and_phi_cycles() { + let Kit { + mut m, + b, + reads, + writes, + .. + } = kit(); + let i32t = m.int(32); + let (zero, one) = (m.i32(0), m.i32(1)); + let (head, exit) = (m.new_block(), m.new_block()); + m.terminate(b, Term::Br(head)); + // A counter that decides the branch, and a register that only + // feeds itself round the loop. + let count = m.phi(head, i32t); + let idle = m.phi(head, i32t); + let next = m.bin(head, Bin::Add, count, one); + let idle_next = m.call(head, reads, vec![idle, one]); + let more = m.cmp(head, pred::IULT, next, one); + m.terminate(head, Term::CondBr(more, head, exit)); + m.set_phi(count, vec![(zero, b), (next, head)]); + m.set_phi(idle, vec![(zero, b), (idle_next, head)]); + m.call(exit, writes, vec![zero, one]); + m.terminate(exit, Term::Ret); + m.optimise(DEAD); + assert_eq!(m.blocks[head].phis.len(), 1, "the counter"); + assert_eq!(body(&m, head), 2, "the step and the test"); + assert_eq!(body(&m, exit), 1); + m.write(); + } + + #[test] + fn wave_operations_have_no_effect_of_their_own() { + let mut k = kit(); + let i32t = k.m.int(32); + let fty = k.m.func_ty(i32t, vec![i32t, i32t]); + let first = k.m.function( + "dx.op.waveReadLaneFirst.i32", + fty, + Some(Attr::NoUnwind), + false, + ); + let barrier = + k.m.function("dx.op.barrier", fty, Some(Attr::NoDuplicate), false); + let one = k.m.i32(1); + k.m.call(k.b, first, vec![one, one]); + k.m.call(k.b, barrier, vec![one, one]); + k.m.terminate(k.b, Term::Ret); + k.m.optimise(DEAD); + assert_eq!(body(&k.m, k.b), 1, "the barrier"); + // The declarations nothing calls any more are gone, and the call + // that stayed names its function by the new number. + let names: Vec<&str> = k.m.funcs.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["main", "dx.op.barrier"]); + let Op::Call(f, _) = k.m.insts[k.m.blocks[k.b].body[0] as usize].op else { + panic!("a call"); + }; + assert_eq!(k.m.funcs[f as usize].name, "dx.op.barrier"); + k.m.write(); + } + + /// The operands of each store left in block `b`. + fn stores(m: &Module, b: usize) -> Vec> { + m.blocks[b] + .body + .iter() + .filter_map(|&i| match &m.insts[i as usize].op { + Op::Call(g, args) if m.funcs[*g as usize].name.contains("Store") => { + Some(args.clone()) + } + _ => None, + }) + .collect() + } + + #[test] + fn constants_and_identities_fold() { + let Kit { + mut m, + b, + reads, + writes, + .. + } = kit(); + let (i32t, f32t) = (m.int(32), m.float()); + let (zero, one, all) = (m.i32(0), m.i32(1), m.i32(u32::MAX)); + let x = m.call(b, reads, vec![one, one]); + // x + 0, -1 & x, x >> 0, x * 1, x | x: all x. + let a = m.bin(b, Bin::Add, x, zero); + let a = m.bin(b, Bin::And, all, a); + let a = m.bin(b, Bin::LShr, a, zero); + let a = m.bin(b, Bin::Mul, a, one); + let a = m.bin(b, Bin::Or, a, a); + // There and back. + let f = m.cast(b, Cast::Bitcast, a, f32t); + let a = m.cast(b, Cast::Bitcast, f, i32t); + // Constants: (262168 >> 16) & 127 = 4, 7 & 31 = 7, -8 >>s 1 = -4. + let k = m.i32(262168); + let sixteen = m.i32(16); + let k = m.bin(b, Bin::LShr, k, sixteen); + let k127 = m.i32(127); + let k = m.bin(b, Bin::And, k, k127); + let minus8 = m.i32(-8i32 as u32); + let s = m.bin(b, Bin::AShr, minus8, one); + // A shift by the width is left alone. + let k32 = m.i32(32); + let wide = m.bin(b, Bin::Shl, one, k32); + // A select between a value and itself, and on a constant. + let c = m.cmp(b, pred::IULT, zero, one); + let sel = m.select(b, c, a, wide); + let same = m.select(b, c, sel, sel); + m.call(b, writes, vec![same, k]); + m.call(b, writes, vec![s, wide]); + m.terminate(b, Term::Ret); + m.optimise(FOLD | DEAD); + assert_eq!(body(&m, b), 4, "the read, the wide shift and two stores"); + let four = m.i32(4); + let minus4 = m.i32(-4i32 as u32); + let stores = stores(&m, b); + assert_eq!(stores, [vec![x, four], vec![minus4, wide]]); + m.write(); + } + + #[test] + fn float_arithmetic_is_not_folded() { + let Kit { + mut m, b, writes, .. + } = kit(); + let f32t = m.float(); + let fty = m.func_ty(f32t, vec![f32t, f32t]); + let input = m.function("dx.op.loadInput.f32", fty, Some(Attr::ReadNone), false); + let (zero, one, two) = (m.f32(0), m.f32(1.0f32.to_bits()), m.f32(2.0f32.to_bits())); + let x = m.call(b, input, vec![zero, zero]); + let y = m.call(b, input, vec![one, one]); + let a = m.bin(b, Bin::Add, x, zero); + let p = m.bin(b, Bin::Mul, a, one); + // The same sum the other way round is another instruction. + let xy = m.bin(b, Bin::Add, x, y); + let yx = m.bin(b, Bin::Add, y, x); + // Constants compare here: 1 < 2, and nothing equals a NaN. + let nan = m.f32(f32::NAN.to_bits()); + let lt = m.cmp(b, pred::OLT, one, two); + let eq = m.cmp(b, pred::OEQ, nan, nan); + let une = m.cmp(b, pred::UNE, nan, one); + let sel = m.select(b, lt, xy, yx); + let sel = m.select(b, eq, p, sel); + let sel = m.select(b, une, sel, p); + m.call(b, writes, vec![sel, p]); + m.terminate(b, Term::Ret); + m.optimise(ALL); + // Two inputs, x + 0.0, * 1.0, x + y and the store: y + x and the + // selects are gone. + assert_eq!(body(&m, b), 6); + assert_eq!(stores(&m, b), [[xy, p]]); + m.write(); + } + + /// entry: `c = x < y`, branch to `then` or `other`, which join. + struct Diamond { + k: Kit, + x: V, + y: V, + c: V, + then: usize, + other: usize, + join: usize, + } + + fn diamond() -> Diamond { + let mut k = kit(); + let (one, two) = (k.m.i32(1), k.m.i32(2)); + let x = k.m.call(k.b, k.reads, vec![one, one]); + let y = k.m.call(k.b, k.reads, vec![two, two]); + let c = k.m.cmp(k.b, pred::IULT, x, y); + let (then, other, join) = (k.m.new_block(), k.m.new_block(), k.m.new_block()); + k.m.terminate(k.b, Term::CondBr(c, then, other)); + k.m.terminate(then, Term::Br(join)); + k.m.terminate(other, Term::Br(join)); + k.m.terminate(join, Term::Ret); + Diamond { + k, + x, + y, + c, + then, + other, + join, + } + } + + #[test] + fn a_value_is_reused_below_its_block_and_not_beside_it() { + let Diamond { + k: + Kit { + mut m, + b, + pure, + writes, + .. + }, + x, + y, + then, + other, + join, + .. + } = diamond(); + // The entry's value again in a branch; a branch's value again in + // the other branch and in the join (neither is on every path). + let top = m.call(b, pure, vec![x, y]); + m.call(b, writes, vec![top, top]); + let again = m.call(then, pure, vec![x, y]); + let side = m.bin(then, Bin::Add, y, x); + m.call(then, writes, vec![again, side]); + let beside = m.bin(other, Bin::Add, x, y); + m.call(other, writes, vec![beside, beside]); + let after = m.bin(join, Bin::Add, x, y); + m.call(join, writes, vec![after, after]); + m.optimise(REUSE); + assert_eq!(stores(&m, then), [[top, side]]); + assert_eq!(body(&m, then), 2); + assert_eq!(body(&m, other), 2); + assert_eq!(body(&m, join), 2); + m.write(); + } + + #[test] + fn a_branch_taken_says_what_its_condition_is() { + let Diamond { + k: + Kit { + mut m, + b, + reads, + writes, + .. + }, + x, + y, + c, + then, + other, + join, + } = diamond(); + let three = m.i32(3); + let d = m.call(b, reads, vec![three, three]); + let d = m.cmp(b, pred::NE, d, three); + let both = m.bin(b, Bin::And, c, d); + // Behind the branch: the condition again (a guard), its opposite + // comparison, and a guarded write. + let guard = m.bin(then, Bin::And, c, d); + let old = m.select(then, guard, x, y); + let not = m.cmp(then, pred::IUGE, x, y); + let new = m.select(then, not, y, old); + m.call(then, writes, vec![new, new]); + let kept = m.select(other, c, x, y); + m.call(other, writes, vec![kept, kept]); + // After the join nothing is known. + let open = m.select(join, c, x, y); + m.call(join, writes, vec![open, open]); + m.optimise(FOLD | FACTS); + // then: select(d, x, y) and the store; other: y is stored. + assert_eq!(body(&m, then), 2); + let V::Inst(sel) = stores(&m, then)[0][0] else { + panic!() + }; + assert!(matches!(m.insts[sel as usize].op, Op::Select(g, a, z) if (g, a, z) == (d, x, y))); + assert_eq!(stores(&m, other), [[y, y]]); + assert_eq!(body(&m, join), 2); + let _ = both; + m.write(); + + // Both terms of an `and` that held hold behind it. + let Diamond { + k: + Kit { + mut m, + b, + reads, + writes, + .. + }, + x, + y, + c, + .. + } = diamond(); + let three = m.i32(3); + let d = m.call(b, reads, vec![three, three]); + let d = m.cmp(b, pred::NE, d, three); + let both = m.bin(b, Bin::And, c, d); + let (inner, out) = (m.new_block(), m.new_block()); + m.terminate(b, Term::CondBr(both, inner, out)); + let a = m.select(inner, c, x, y); + let z = m.select(inner, d, a, y); + m.call(inner, writes, vec![z, z]); + m.terminate(inner, Term::Br(out)); + // Where the `and` did not hold either term may. + let w = m.select(out, d, x, y); + m.call(out, writes, vec![w, w]); + m.terminate(out, Term::Ret); + m.optimise(FOLD | FACTS); + assert_eq!(stores(&m, inner), [[x, x]]); + assert_eq!(body(&m, out), 2); + m.write(); + } + + #[test] + fn a_branch_on_a_constant_goes_one_way() { + let Diamond { + k: Kit { + mut m, b, writes, .. + }, + x, + y, + c, + then, + other, + join, + } = diamond(); + let i32t = m.int(32); + // Behind the branch the same test again: its other side is never + // run, and the join behind it has one value. + let (deep, never, meet) = (m.new_block(), m.new_block(), m.new_block()); + m.terminate(then, Term::CondBr(c, deep, never)); + m.terminate(deep, Term::Br(meet)); + m.call(never, writes, vec![y, y]); + m.terminate(never, Term::Br(meet)); + let p = m.phi(meet, i32t); + m.set_phi(p, vec![(x, deep), (y, never)]); + m.call(meet, writes, vec![p, p]); + m.terminate(meet, Term::Br(join)); + let q = m.phi(join, i32t); + m.set_phi(q, vec![(p, meet), (y, other)]); + m.call(join, writes, vec![q, q]); + m.optimise(ALL); + assert!(matches!(m.blocks[then].term, Some(Term::Br(t)) if t == deep)); + assert_eq!(stores(&m, meet), [[x, x]]); + assert!(m.blocks[meet].phis.is_empty()); + assert_eq!(body(&m, never), 0, "emptied: nothing reaches it"); + let Op::Phi(incoming) = &m.insts[m.blocks[join].phis[0] as usize].op else { + panic!() + }; + assert_eq!(incoming, &vec![(x, meet), (y, other)]); + let _ = b; + m.write(); + } + + #[test] + fn a_read_is_reused_within_its_block_until_a_store() { + let Diamond { + k: + Kit { + mut m, + b, + reads, + writes, + .. + }, + x, + y, + then, + .. + } = diamond(); + let i32t = m.int(32); + // The entry reads (1, 1) for x: again in the entry it is x; in the + // next block it is read again. + let one = m.i32(1); + let again = m.call(b, reads, vec![one, one]); + m.call(b, writes, vec![again, y]); + let after = m.call(b, reads, vec![one, one]); + let twice = m.call(b, reads, vec![one, one]); + let sum = m.bin(b, Bin::Add, after, twice); + m.call(b, writes, vec![sum, sum]); + let below = m.call(then, reads, vec![one, one]); + m.call(then, writes, vec![below, below]); + // A constant buffer cannot change: one load for the function. + let cfty = m.func_ty(i32t, vec![i32t, i32t]); + let cb = m.function( + "dx.op.cbufferLoadLegacy.i32", + cfty, + Some(Attr::ReadOnly), + false, + ); + let top = m.call(b, cb, vec![one, one]); + m.call(b, writes, vec![top, top]); + let under = m.call(then, cb, vec![one, one]); + m.call(then, writes, vec![under, under]); + m.optimise(REUSE | LOADS); + let stores = stores(&m, b); + assert_eq!(stores[0], [x, y], "the second read is the first"); + let V::Inst(sum) = stores[1][0] else { panic!() }; + assert!( + matches!(m.insts[sum as usize].op, Op::Bin(Bin::Add, a, z) if a == after && z == after), + "read again after the store, once" + ); + assert_eq!(stores[2], [top, top]); + assert_eq!( + super::tests::stores(&m, then), + [vec![below, below], vec![top, top]] + ); + m.write(); + } + + #[test] + fn a_join_of_one_value_and_two_equal_joins() { + let Diamond { + k: Kit { mut m, writes, .. }, + x, + y, + then, + other, + join, + .. + } = diamond(); + let i32t = m.int(32); + let one = m.phi(join, i32t); + m.set_phi(one, vec![(x, then), (x, other)]); + let p = m.phi(join, i32t); + m.set_phi(p, vec![(x, then), (y, other)]); + let q = m.phi(join, i32t); + m.set_phi(q, vec![(y, other), (x, then)]); + m.call(join, writes, vec![one, p]); + let sum = m.bin(join, Bin::Add, p, q); + m.call(join, writes, vec![sum, q]); + m.optimise(FOLD | REUSE); + assert_eq!( + m.blocks[join].phis, + [match p { + V::Inst(i) => i, + _ => unreachable!(), + }] + ); + let stores = stores(&m, join); + assert_eq!(stores[0], [x, p]); + assert_eq!(stores[1][1], p); + m.write(); + } + + // ---- the passes against an interpreter, on random programs ---- + + /// Runs `m` on `inputs`: the stores it makes, in order (and how it + /// ended). Reads a value before its definition ran: a panic. + fn run(m: &Module, inputs: &[u32]) -> Vec<(String, Vec)> { + let mut vals: Vec> = vec![None; m.insts.len()]; + let mut memory = [0u64; 16]; + let mut trace = Vec::new(); + let eval = |vals: &[Option], v: V| -> u64 { + match v { + V::Inst(i) => vals[i as usize].expect("a value defined before its use"), + V::Const(c) => { + match (&m.consts[c as usize].1, m.int_bits(m.consts[c as usize].0)) { + (Const::Int(x), Some(bits)) => *x as u64 & mask(bits), + (Const::Float(bits), _) => u64::from(*bits), + _ => 0, + } + } + _ => panic!("a global or function as a value"), + } + }; + let (mut b, mut from) = (0usize, usize::MAX); + for _ in 0..4000 { + let blk = &m.blocks[b]; + // Joins take their values together, before any is assigned. + let joined: Vec<(u32, u64)> = blk + .phis + .iter() + .map(|&p| { + let Op::Phi(incoming) = &m.insts[p as usize].op else { + panic!("a join") + }; + let v = incoming + .iter() + .find(|x| x.1 == from) + .expect("a value for the edge taken"); + (p, eval(&vals, v.0)) + }) + .collect(); + for (p, x) in joined { + vals[p as usize] = Some(x); + } + for &i in &blk.body { + let inst = &m.insts[i as usize]; + let bits = m.int_bits(inst.ty); + let float = |x: u64| f32::from_bits(x as u32); + let r = match &inst.op { + Op::Bin(op, x, y) => { + let (x, y) = (eval(&vals, *x), eval(&vals, *y)); + match bits { + Some(bits) => { + let r = match op { + Bin::Add => x.wrapping_add(y), + Bin::Sub => x.wrapping_sub(y), + Bin::Mul => x.wrapping_mul(y), + Bin::And => x & y, + Bin::Or => x | y, + Bin::Xor => x ^ y, + Bin::Shl => x << y, + Bin::LShr => x >> y, + Bin::AShr => (signed(bits, x) >> y) as u64, + _ => panic!("no divisions here"), + }; + r & mask(bits) + } + None => { + let (x, y) = (float(x), float(y)); + let r = match op { + Bin::Add => x + y, + Bin::Sub => x - y, + _ => x * y, + }; + u64::from(r.to_bits()) + } + } + } + Op::Cmp(p, x, y) => { + let wide = m.int_bits(m.type_of(*x)); + let (x, y) = (eval(&vals, *x), eval(&vals, *y)); + let holds = match wide { + Some(bits) => { + let (sx, sy) = (signed(bits, x), signed(bits, y)); + match *p { + pred::EQ => x == y, + pred::NE => x != y, + pred::IUGT => x > y, + pred::IUGE => x >= y, + pred::IULT => x < y, + pred::IULE => x <= y, + pred::SGT => sx > sy, + pred::SGE => sx >= sy, + pred::SLT => sx < sy, + _ => sx <= sy, + } + } + None => { + let (x, y) = (float(x), float(y)); + if x.is_nan() || y.is_nan() { + p & 8 != 0 + } else { + (p & 1 != 0 && x == y) + || (p & 2 != 0 && x > y) + || (p & 4 != 0 && x < y) + } + } + }; + u64::from(holds) + } + Op::Select(c, t, f) => { + if eval(&vals, *c) != 0 { + eval(&vals, *t) + } else { + eval(&vals, *f) + } + } + Op::Cast(op, x) => { + let from_bits = m.int_bits(m.type_of(*x)); + let x = eval(&vals, *x); + match (op, from_bits, bits) { + (Cast::Bitcast, _, _) => x, + (Cast::ZExt, _, _) => x, + (Cast::SExt, Some(f), Some(t)) => signed(f, x) as u64 & mask(t), + (Cast::Trunc, _, Some(t)) => x & mask(t), + _ => panic!("a cast the generator does not make"), + } + } + Op::Call(f, args) => { + let a: Vec = args.iter().map(|&v| eval(&vals, v)).collect(); + let name = m.funcs[*f as usize].name.as_str(); + match name { + "dx.op.loadInput.i32" => { + u64::from(inputs[(a[0] ^ a[1]) as usize % inputs.len()]) + } + "dx.op.binary.i32" => a[0].min(a[1]), + "dx.op.cbufferLoadLegacy.i32" => u64::from( + inputs[a[0] as usize % inputs.len()].rotate_left(a[1] as u32 & 31), + ), + "dx.op.bufferLoad.i32" => memory[(a[0] ^ a[1]) as usize % 16], + "dx.op.waveReadLaneFirst.i32" => a[0] ^ a[1], + _ => { + memory[a[0] as usize % 16] = a[1]; + trace.push((name.to_owned(), a)); + 0 + } + } + } + _ => panic!("an instruction the generator does not make"), + }; + vals[i as usize] = Some(r); + } + from = b; + b = match blk.term.expect("a terminator") { + Term::Ret => { + trace.push(("ret".into(), Vec::new())); + return trace; + } + Term::Br(t) => t, + Term::CondBr(c, t, f) => { + if eval(&vals, c) != 0 { + t + } else { + f + } + } + }; + } + trace.push(("still running".into(), Vec::new())); + trace + } + + /// A random structured program over a few registers, as the lowering + /// makes them: every register joined at every join, conditions tested + /// again behind their branch, values computed again. + struct Gen { + k: Kit, + rng: u64, + regs: Vec, + conds: Vec, + cur: usize, + input: V, + table: V, + wave: V, + /// The operands of the block's last read (to read the place again, + /// and to store to it). + last: Option<(V, V)>, + } + + impl Gen { + fn next(&mut self, n: u64) -> u64 { + self.rng ^= self.rng << 13; + self.rng ^= self.rng >> 7; + self.rng ^= self.rng << 17; + (self.rng >> 11) % n + } + + fn reg(&mut self) -> V { + let n = self.next(self.regs.len() as u64) as usize; + self.regs[n] + } + + /// A register or a small constant. + fn value(&mut self) -> V { + match self.next(4) { + 0 => { + let k = [0u32, 1, 2, 31, u32::MAX, 0x8000_0000, 7][self.next(7) as usize]; + self.k.m.i32(k) + } + _ => self.reg(), + } + } + + fn cond(&mut self) -> V { + let c = self.cur; + let made = match self.next(6) { + 0 if !self.conds.is_empty() => { + let n = self.next(self.conds.len() as u64) as usize; + return self.conds[n]; + } + 1 if self.conds.len() > 1 => { + let (a, b) = ( + self.next(self.conds.len() as u64), + self.next(self.conds.len() as u64), + ); + let op = [Bin::And, Bin::Or, Bin::Xor][self.next(3) as usize]; + self.k + .m + .bin(c, op, self.conds[a as usize], self.conds[b as usize]) + } + 2 if !self.conds.is_empty() => { + let n = self.next(self.conds.len() as u64) as usize; + let t = self.k.m.bool(true); + self.k.m.bin(c, Bin::Xor, self.conds[n], t) + } + _ => { + let p = pred::EQ + self.next(10) as u8; + let (x, y) = (self.reg(), self.value()); + self.k.m.cmp(c, p, x, y) + } + }; + self.conds.push(made); + made + } + + fn statement(&mut self) { + let c = self.cur; + let d = self.next(self.regs.len() as u64) as usize; + let i32t = self.k.m.int(32); + let f32t = self.k.m.float(); + let r = match self.next(14) { + 0..=3 => { + let op = [Bin::Add, Bin::Sub, Bin::Mul, Bin::And, Bin::Or, Bin::Xor] + [self.next(6) as usize]; + let (x, y) = (self.value(), self.value()); + self.k.m.bin(c, op, x, y) + } + 4 => { + let op = [Bin::Shl, Bin::LShr, Bin::AShr][self.next(3) as usize]; + let x = self.value(); + let by = self.next(32) as u32; + let by = self.k.m.i32(by); + self.k.m.bin(c, op, x, by) + } + 5 | 6 => { + // A guarded write: the old value where the guard fails. + let g = self.cond(); + let x = self.value(); + self.k.m.select(self.cur, g, x, self.regs[d]) + } + 7 => { + let (x, y) = (self.value(), self.value()); + let f = [self.k.pure, self.input, self.table, self.wave][self.next(4) as usize]; + self.k.m.call(c, f, vec![x, y]) + } + 8 | 9 => { + let again = self.next(2) == 0; + let (x, y) = match self.last { + Some(last) if again => last, + _ => (self.value(), self.value()), + }; + self.last = Some((x, y)); + self.k.m.call(c, self.k.reads, vec![x, y]) + } + 10 => { + // A store, half the time to the place read last. + let (mut x, y) = (self.value(), self.value()); + let there = self.next(2) == 0; + if let Some((a, b)) = self.last + && there + { + x = self.k.m.bin(c, Bin::Xor, a, b); + } + self.k.m.call(c, self.k.writes, vec![x, y]); + return; + } + 11 => { + // Float arithmetic, read back as bits. + let (x, y) = (self.value(), self.value()); + let (x, y) = ( + self.k.m.cast(c, Cast::Bitcast, x, f32t), + self.k.m.cast(c, Cast::Bitcast, y, f32t), + ); + let op = [Bin::Add, Bin::Sub, Bin::Mul][self.next(3) as usize]; + let f = self.k.m.bin(c, op, x, y); + if self.next(2) == 0 { + let p = self.next(16) as u8; + let t = self.k.m.cmp(c, p, f, y); + self.conds.push(t); + } + self.k.m.cast(c, Cast::Bitcast, f, i32t) + } + 12 => { + let g = self.cond(); + self.k.m.cast(self.cur, Cast::ZExt, g, i32t) + } + _ => { + let x = self.value(); + let f = self.k.m.cast(c, Cast::Bitcast, x, f32t); + self.k.m.cast(c, Cast::Bitcast, f, i32t) + } + }; + self.regs[d] = r; + } + + fn code(&mut self, depth: u32) { + for _ in 0..1 + self.next(6) { + match self.next(8) { + 0 | 1 if depth > 0 => self.branch(depth - 1), + 2 if depth > 0 => self.repeat(depth - 1), + _ => self.statement(), + } + } + } + + /// if / else, every register joined. + fn branch(&mut self, depth: u32) { + let c = self.cond(); + let i32t = self.k.m.int(32); + let (then, other, join) = ( + self.k.m.new_block(), + self.k.m.new_block(), + self.k.m.new_block(), + ); + self.k.m.terminate(self.cur, Term::CondBr(c, then, other)); + let (before, known) = (self.regs.clone(), self.conds.len()); + self.cur = then; + self.last = None; + self.code(depth); + let (then_regs, then_end) = (std::mem::replace(&mut self.regs, before), self.cur); + self.k.m.terminate(then_end, Term::Br(join)); + self.conds.truncate(known); + self.cur = other; + self.last = None; + if self.next(3) != 0 { + self.code(depth); + } + let other_end = self.cur; + self.k.m.terminate(other_end, Term::Br(join)); + self.conds.truncate(known); + for (r, &t) in then_regs.iter().enumerate() { + let p = self.k.m.phi(join, i32t); + self.k + .m + .set_phi(p, vec![(t, then_end), (self.regs[r], other_end)]); + self.regs[r] = p; + } + self.cur = join; + self.last = None; + } + + /// A loop that runs at most a few times, every register joined at + /// its head. + fn repeat(&mut self, depth: u32) { + let i32t = self.k.m.int(32); + let (head, exit) = (self.k.m.new_block(), self.k.m.new_block()); + let before = self.cur; + self.k.m.terminate(before, Term::Br(head)); + let entering = self.regs.clone(); + let joins: Vec = (0..self.regs.len()) + .map(|_| self.k.m.phi(head, i32t)) + .collect(); + let count = self.k.m.phi(head, i32t); + self.regs = joins.clone(); + let known = self.conds.len(); + self.cur = head; + self.last = None; + self.code(depth); + let one = self.k.m.i32(1); + let next = self.k.m.bin(self.cur, Bin::Add, count, one); + let limit = 1 + self.next(3) as u32; + let limit = self.k.m.i32(limit); + let mut more = self.k.m.cmp(self.cur, pred::IULT, next, limit); + if self.next(2) == 0 { + let c = self.cond(); + more = self.k.m.bin(self.cur, Bin::And, more, c); + } + let latch = self.cur; + self.k.m.terminate(latch, Term::CondBr(more, head, exit)); + for (r, &p) in joins.iter().enumerate() { + self.k + .m + .set_phi(p, vec![(entering[r], before), (self.regs[r], latch)]); + } + let zero = self.k.m.i32(0); + self.k.m.set_phi(count, vec![(zero, before), (next, latch)]); + self.conds.truncate(known); + self.cur = exit; + self.last = None; + } + } + + fn random_program(seed: u64) -> Module { + let mut k = kit(); + let i32t = k.m.int(32); + let fty = k.m.func_ty(i32t, vec![i32t, i32t]); + let input = + k.m.function("dx.op.loadInput.i32", fty, Some(Attr::ReadNone), false); + let table = k.m.function( + "dx.op.cbufferLoadLegacy.i32", + fty, + Some(Attr::ReadOnly), + false, + ); + let wave = k.m.function( + "dx.op.waveReadLaneFirst.i32", + fty, + Some(Attr::NoUnwind), + false, + ); + let b = k.b; + let mut g = Gen { + k, + rng: seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1, + regs: Vec::new(), + conds: Vec::new(), + cur: b, + input, + table, + wave, + last: None, + }; + for r in 0..5 { + let (x, y) = (g.k.m.i32(r), g.k.m.i32(r * 3)); + let v = g.k.m.call(b, input, vec![x, y]); + g.regs.push(v); + } + g.code(3); + g.code(2); + // Every register is read at the end. + for r in 0..g.regs.len() { + let at = g.k.m.i32(r as u32); + g.k.m.call(g.cur, g.k.writes, vec![at, g.regs[r]]); + } + g.k.m.terminate(g.cur, Term::Ret); + g.k.m + } + + #[test] + fn every_pass_leaves_what_random_programs_store() { + let mut removed = 0; + for seed in 1..=400u64 { + let plain = random_program(seed); + let inputs: Vec> = (0..6u32) + .map(|n| { + (0..7u32) + .map(|i| match n { + 0 => 0, + 1 => i, + 2 => u32::MAX - i, + _ => { + (seed as u32 ^ n) + .wrapping_mul(0x9E37_79B9) + .rotate_left(i * 5) + ^ (i << 28) + } + }) + .collect() + }) + .collect(); + let expected: Vec<_> = inputs.iter().map(|i| run(&plain, i)).collect(); + let written: usize = plain + .blocks + .iter() + .map(|b| b.body.len() + b.phis.len()) + .sum(); + for passes in [ + DEAD, + FOLD, + REUSE, + FACTS, + LOADS, + FOLD | FACTS, + FOLD | REUSE | DEAD, + ALL, + ] { + let mut m = random_program(seed); + m.optimise(passes); + for (i, want) in inputs.iter().zip(&expected) { + assert_eq!(&run(&m, i), want, "seed {seed}, passes {passes}"); + } + if passes == ALL { + let left: usize = m.blocks.iter().map(|b| b.body.len() + b.phis.len()).sum(); + removed += written - left; + } + m.write(); + } + } + // The programs are of the wasteful kind: the passes find work. + assert!(removed > 4000, "{removed} instructions removed"); + } +} diff --git a/crates/victory-shader/src/emit/bvh_tests.rs b/crates/victory-shader/src/emit/bvh_tests.rs deleted file mode 100644 index 2a7305f..0000000 --- a/crates/victory-shader/src/emit/bvh_tests.rs +++ /dev/null @@ -1,488 +0,0 @@ -//! The ray intersection emulation (`lower/bvh.rs`) and title memory through -//! the address map (`lower/global.rs`), against a CPU model of the -//! instruction: Microsoft's software model in the XDXR traversal headers -//! (`SoftwareBvhIntersectRay`, `TestXboxBvh4Node`, `TestXboxBvh4Leaf`), -//! transcribed. On a GPU, a program reads rays through the map, tests -//! them against hand-built nodes and stores the results through the map. - -const INF: u32 = 0x7F80_0000; -const ONE: u32 = 0x3F80_0000; -const INVALID: u32 = u32::MAX; - -#[derive(Debug, Clone, Copy)] -struct Ray { - origin: [f32; 3], - dir: [f32; 3], - inv: [f32; 3], - extent: f32, -} - -impl Ray { - fn new(origin: [f32; 3], dir: [f32; 3], extent: f32) -> Ray { - Ray { - origin, - dir, - inv: dir.map(|d| 1.0 / d), - extent, - } - } -} - -/// The model of `image_bvh_intersect_ray` on `node` (a pointer into -/// `bvh`, a buffer of dwords at the descriptor's base). -fn intersect(bvh: &[u32], node: u32, r: &Ray, sort: bool, _ij: bool) -> [u32; 4] { - // The reference is the crate's own model (watertight: a ray exactly - // on a shared edge hits both triangles), which the upstream card - // tests prove against the hardware. - let at = ((node >> 3) * 16) as usize; - let mut n = [0u32; 28]; - let take = (bvh.len() - at).min(28); - n[..take].copy_from_slice(&bvh[at..at + take]); - let ray = crate::bvh::Ray { - extent: r.extent, - origin: r.origin, - direction: r.dir, - inverse: r.inv, - }; - crate::bvh::intersect(&n, node & 7, &ray, sort) -} - -fn f3(v: [f32; 3]) -> [u32; 3] { - v.map(f32::to_bits) -} - -/// Six halves of a box: min x y, min z max x, max y z. -fn box16(lo: [f32; 3], hi: [f32; 3]) -> [u32; 3] { - let h = |x: f32| -> u32 { - // Exact for the small dyadic values the tests use. - let b = x.to_bits(); - if x == 0.0 { - return (b >> 16) & 0x8000; - } - let e = ((b >> 23) & 0xFF) as i32 - 127 + 15; - assert!( - (1..31).contains(&e) && b & 0x1FFF == 0, - "{x} is no exact half" - ); - (b >> 16) & 0x8000 | (e as u32) << 10 | (b >> 13) & 0x3FF - }; - [ - h(lo[0]) | h(lo[1]) << 16, - h(lo[2]) | h(hi[0]) << 16, - h(hi[1]) | h(hi[2]) << 16, - ] -} - -/// The test BVH: a leaf (unit 0), a float box node (units 2-3) and a -/// half box node (unit 4), with their pointers. -fn scene() -> (Vec, [u32; 4], u32, u32) { - let mut bvh = vec![0u32; 16 * 6]; - let verts: [[f32; 3]; 5] = [ - [0.0, 0.0, 0.0], - [1.0, 0.0, 0.0], - [0.0, 1.0, 0.0], - [1.0, 1.0, 0.0], - [0.0, 0.0, 1.0], - ]; - for (k, v) in verts.iter().enumerate() { - bvh[3 * k..3 * k + 3].copy_from_slice(&f3(*v)); - } - // TRI0 i=V j=W, TRI1 i=W j=U, TRI2 i=U j=V, TRI3 i=V j=U. - bvh[15] = 0x09 | 0x02 << 8 | 0x04 << 16 | 0x01 << 24; - let boxes: [([f32; 3], [f32; 3]); 4] = [ - ([0.0, 0.0, -3.0], [1.0, 1.0, -2.0]), - ([0.0, 0.0, -1.0], [1.0, 1.0, 0.0]), - // Inverted bounds: per-axis min/max normalizes the box. - ([1.0, 1.0, 1.0], [0.0, 0.0, 0.0]), - ([0.0, 0.0, -6.0], [1.0, 1.0, -5.0]), - ]; - let children = [0x105, 0x204, 0x300, 0x401]; - let full = 2 * 16; - bvh[full..full + 4].copy_from_slice(&children); - for (k, (lo, hi)) in boxes.iter().enumerate() { - let b = full + 4 + 6 * k; - bvh[b..b + 3].copy_from_slice(&f3(*lo)); - bvh[b + 3..b + 6].copy_from_slice(&f3(*hi)); - } - let small = 4 * 16; - bvh[small..small + 4].copy_from_slice(&children); - for (k, (lo, hi)) in boxes.iter().enumerate() { - let b = small + 4 + 3 * k; - bvh[b..b + 3].copy_from_slice(&box16(*lo, *hi)); - } - let leaf = [0, 1, 2, 3]; - (bvh, leaf, (2 << 3) | 5, (4 << 3) | 4) -} - -/// 32 (node, ray) cases: every triangle, shared edges, parallel and -/// backward rays, back faces, both box kinds with sorting, a short extent -/// and misses, then seeded random rays at the boxes. -fn cases() -> Vec<(u32, Ray)> { - let (_, tri, full, small) = scene(); - let down = |x, y| Ray::new([x, y, 5.0], [0.0, 0.0, -1.0], 100.0); - let mut c = vec![ - (tri[0], down(0.25, 0.25)), - (tri[1], down(0.25, 0.25)), - (tri[0], down(0.75, 0.75)), - (tri[1], down(0.75, 0.75)), - // On the edge TRI0 and TRI1 share: watertight means both hit it. - (tri[0], down(0.5, 0.5)), - (tri[1], down(0.5, 0.5)), - (tri[2], down(0.25, 0.5)), - (tri[3], Ray::new([-1.0, 0.25, 0.25], [1.0, 0.0, 0.0], 100.0)), - // In the triangle's plane, and moving away from it. - (tri[0], Ray::new([-1.0, 0.25, 0.0], [1.0, 0.0, 0.0], 100.0)), - ( - tri[0], - Ray::new([0.25, 0.25, -5.0], [0.0, 0.0, -1.0], 100.0), - ), - // From below: the back face. - (tri[0], Ray::new([0.25, 0.25, -5.0], [0.0, 0.0, 1.0], 100.0)), - ( - tri[1], - Ray::new([0.5, 0.25, 4.0], [0.125, 0.25, -1.0], 100.0), - ), - (full, down(0.5, 0.5)), - (full, Ray::new([0.5, 0.5, 5.0], [0.0, 0.0, -1.0], 6.0)), - (full, down(1.5, 0.5)), - (full, Ray::new([0.5, 0.5, -2.5], [1.0, 0.0, 0.0], 100.0)), - (small, down(0.5, 0.5)), - (small, Ray::new([0.5, 0.5, 5.0], [0.0, 0.0, -1.0], 6.0)), - (small, down(1.5, 0.5)), - (small, Ray::new([0.5, 0.5, -2.5], [1.0, 0.0, 0.0], 100.0)), - ]; - let mut seed = 0x1234_5678u32; - let mut rand = || { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - (seed >> 8) as f32 / (1u32 << 24) as f32 * 4.0 - 2.0 - }; - while c.len() < 32 { - let node = if c.len() % 2 == 0 { full } else { small }; - // Over the boxes' footprint (x, y in [0, 1]), give or take. - let origin = [0.5 + rand() * 0.35, 0.5 + rand() * 0.35, rand() + 4.0]; - let dir = [rand() * 0.25, rand() * 0.25, -1.0 - rand().abs()]; - c.push((node, Ray::new(origin, dir, 2.0 + rand().abs() * 4.0))); - } - c -} - -#[test] -fn model_hits_and_orders_as_expected() { - let (bvh, tri, full, _) = scene(); - let r = Ray::new([0.25, 0.25, 5.0], [0.0, 0.0, -1.0], 100.0); - let hit = intersect(&bvh, tri[0], &r, true, true); - let t = f32::from_bits(hit[0]) / f32::from_bits(hit[1]); - assert_eq!(t, 5.0); - assert_eq!(intersect(&bvh, tri[1], &r, true, true), [INF, ONE, 0, 0]); - // Barycentrics: TRI0 remaps i to V, j to W. - let (i, j) = ( - f32::from_bits(hit[2]) / f32::from_bits(hit[1]), - f32::from_bits(hit[3]) / f32::from_bits(hit[1]), - ); - assert!( - (i - 0.25).abs() < 1e-6 && (j - 0.25).abs() < 1e-6, - "{i} {j}" - ); - let mid = Ray::new([0.5, 0.5, 5.0], [0.0, 0.0, -1.0], 100.0); - // Watertight: a ray exactly on the shared edge hits both triangles. - let owners = [tri[0], tri[1]] - .iter() - .filter(|&&n| intersect(&bvh, n, &mid, true, true)[0] != INF) - .count(); - assert_eq!(owners, 2, "a ray on a shared edge hits both triangles"); - let mid = Ray::new([0.5, 0.5, 5.0], [0.0, 0.0, -1.0], 100.0); - // The inverted box's per-axis min/max normalizes it: the ray enters - // all four boxes, sorted by entry distance or in child order. - assert_eq!( - intersect(&bvh, full, &mid, true, true), - [0x300, 0x204, 0x105, 0x401] - ); - assert_eq!( - intersect(&bvh, full, &mid, false, true), - [0x105, 0x204, 0x300, 0x401] - ); -} - -#[test] -fn the_cases_cover_hits_misses_and_boxes() { - let (bvh, ..) = scene(); - let (mut hits, mut misses, mut box_hits, mut box_misses) = (0, 0, 0, 0); - for (node, r) in cases() { - let got = intersect(&bvh, node, &r, true, true); - match (node & 7 > 3, got[0] == INF || got == [INVALID; 4]) { - (false, false) => hits += 1, - (false, true) => misses += 1, - (true, false) => box_hits += 1, - (true, true) => box_misses += 1, - } - } - assert!(hits >= 5 && misses >= 4, "{hits} hits, {misses} misses"); - assert!( - box_hits >= 10 && box_misses >= 2, - "{box_hits} box hits, {box_misses} misses" - ); -} - -#[cfg(windows)] -mod gpu { - use super::super::host::{Dispatch, Host, Root, Stride, View}; - use super::super::lower::intersect::TEST_MEMORY; - use super::super::{HostShader, lower, validator}; - use super::*; - use crate::native::{ - ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, - }; - use crate::{io, ir, resource, structure}; - - const BVH: u64 = 0x2_0000_0100; - - /// Per lane: 12 dwords of ray at `48 * lane` of the record buffer - /// (node, extent, origin, direction, inverse direction), read through - /// the descriptor the table's SRV entry builds; the intersection with - /// the descriptor `s[16:19]`, 4 dwords stored at `16 * lane` through - /// the UAV entry's descriptor. An access whose address is title - /// memory lowers through the host's directory, which the test has no - /// copies for, so the reads and the write go through descriptors. - /// `desc1`/`desc3` are the descriptor's flag dwords, written as - /// literals like the console compiler does. - fn program(desc0: u32, desc1: u32, desc3: u32) -> Vec { - let w = vec![ - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 - 0xF408_0302, - 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 - 0x3402_0086, // v_lshlrev_b32 v1, 6, v0 - 0xE038_1000, - 0x8002_0201, // buffer_load_dwordx4 v[2:5], v1, s[8:11], 0 offen - 0xE038_1010, - 0x8002_0601, // buffer_load_dwordx4 v[6:9], v1, s[8:11], 0 offen offset:16 - 0xE038_1020, - 0x8002_0A01, // buffer_load_dwordx4 v[10:13], v1, s[8:11], 0 offen offset:32 - 0xBE90_03FF, - desc0, // s_mov_b32 s16, desc0 - 0xBE91_03FF, - desc1, // s_mov_b32 s17, desc1 - 0xBE92_03C1, // s_mov_b32 s18, -1 - 0xBE93_03FF, - desc3, // s_mov_b32 s19, desc3 - 0xF198_9F01, // image_bvh_intersect_ray v[14:17], v[2:12], s[16:19] - 0x0004_0E02, - 0x3402_0084, // v_lshlrev_b32 v1, 4, v0 - 0xE078_1000, - 0x8003_0E01, // buffer_store_dwordx4 v[14:17], v1, s[12:15], 0 offen - 0xBF81_0000, // s_endpgm - ]; - let names: Vec<_> = - crate::gfx10::decode(&w.iter().flat_map(|x| x.to_le_bytes()).collect::>()) - .expect("decode") - .iter() - .map(|i| i.name().unwrap_or("?")) - .collect(); - assert_eq!( - names, - [ - "s_mov_b32", - "s_load_dwordx4", - "s_load_dwordx4", - "v_lshlrev_b32", - "buffer_load_dwordx4", - "buffer_load_dwordx4", - "buffer_load_dwordx4", - "s_mov_b32", - "s_mov_b32", - "s_mov_b32", - "s_mov_b32", - "image_bvh_intersect_ray", - "v_lshlrev_b32", - "buffer_store_dwordx4", - "s_endpgm" - ] - ); - w - } - - fn build(sort: bool, ij: bool) -> HostShader { - let base = BVH >> 8; - let desc0 = base as u32; - let desc1 = (base >> 32) as u32 & 0xFF | u32::from(sort) << 31; - let desc3 = 0x88FF_FFFF | u32::from(ij) << 24; - let table = |kind, at| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords: at, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 4, - slot: 1, - }; - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 32, - layout: vec![ - RootParam { - root: RootType::Constants, - table_offset_dwords: 0, - sgprs: 4, - base_register: 0, - user_data: 0, - slot: 0, - }, - RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 4, - slot: 1, - }, - ], - used: vec![table(ResourceType::Srv, 0), table(ResourceType::Uav, 8)], - io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, - threads: [32, 1, 1], - }), - code: program(desc0, desc1, desc3) - .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"); - assert!(res.scalar.iter().all(|s| s.1.param != resource::CODE)); - let io = io::raise(&p, &native).expect("io::raise"); - let lowered = lower::lower(&lower::Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: Vec::new(), - outputs: Vec::new(), - prims: Vec::new(), - crumbs: None, - emulate_mesh: false, - mesh_stride: 0, - }) - .expect("lower"); - let shader = HostShader { - stage: HwStage::Cs, - dxil: lowered.dxil, - user_data: lowered.user_data, - samplers: lowered.samplers, - static_samplers: Vec::new(), - root_cbvs: lowered.root_cbvs, - root_srvs: lowered.root_srvs, - address_map: lowered.address_map, - descriptor_words: lowered.descriptor_words, - root_uavs: lowered.root_uavs, - root_indexed_views: Vec::new(), - mesh_emu: None, - }; - if let Ok(mut v) = - validator::Validator::load(validator::Validator::default_path().as_deref()) - { - v.validate(&mut shader.dxil.clone()) - .expect("DXIL validation failed"); - } else { - eprintln!("no dxil.dll; validation skipped"); - } - shader - } - - fn close(a: f32, b: f32) -> bool { - (a - b).abs() <= 1e-5 * a.abs().max(b.abs()).max(1.0) - } - - #[test] - fn bvh_program_tracks_and_lowers() { - build(true, true); - build(false, true); - } - - #[test] - fn bvh_intersection_matches_the_model_on_the_gpu() { - let (bvh, ..) = scene(); - let cases = cases(); - // One buffer like the upstream tests: 64-byte records, then the - // nodes. A record's node pointer counts the records region in, so - // `(pointer >> 3) << 6` lands on the node's byte in the buffer. - let records = cases.len() * 64; - let data: Vec = cases - .iter() - .flat_map(|(node, r)| { - let mut w = vec![(records / 8) as u32 + node, r.extent.to_bits()]; - w.extend(f3(r.origin)); - w.extend(f3(r.dir)); - w.extend(f3(r.inv)); - w.extend([0; 5]); - w - }) - .chain(bvh.iter().copied()) - .collect(); - let _one = super::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; - }; - for (sort, ij) in [(true, true), (false, true)] { - // Heap slot 0: the records and nodes; the buffer's bytes - // map to title address BVH on, so a node read lands on - // its byte past the records region. Set before `build`: - // the hook fires while the DXIL is lowered. - TEST_MEMORY.set(Some((0, BVH))); - let shader = build(sort, ij); - let (root, pso) = host - .compute_pipeline(&shader) - .unwrap_or_else(|e| panic!("{label}: {e}")); - let out = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![(0, Root::Constants(vec![0; 5]))], - views: &[ - View::Buffer { - data: &data, - stride: Stride::Raw, - }, - View::RawUav(128), - ], - samplers: &[], - groups: [1, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{label}: {e}")); - TEST_MEMORY.set(None); - let got = &out[0]; - for (lane, (node, r)) in cases.iter().enumerate() { - let want = intersect(&bvh, *node, r, sort, ij); - let g = &got[4 * lane..4 * lane + 4]; - let what = format!( - "{label} sort={sort} ij={ij} lane {lane} node {node:#x}: got {g:x?}, want {want:x?}" - ); - if node & 7 > 3 || want[0] == INF { - assert_eq!(g, want, "{what}"); - continue; - } - assert_ne!(g[0], INF, "{what}"); - let f = |x: u32| f32::from_bits(x); - let (gd, wd) = (f(g[1]), f(want[1])); - assert!(close(f(g[0]) / gd, f(want[0]) / wd), "{what}: t"); - if ij { - assert!(close(f(g[2]) / gd, f(want[2]) / wd), "{what}: i"); - assert!(close(f(g[3]) / gd, f(want[3]) / wd), "{what}: j"); - } else { - assert_eq!(g[2..], want[2..], "{what}"); - } - } - } - } - } -} diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index 62af883..3c346d9 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -1,7 +1,7 @@ //! The PC container around emitted DXIL: feature flags (`SFI0`), the //! signatures (`ISG1`, `OSG1`), pipeline state validation (`PSV0`) and the -//! program (`DXIL`), laid out as validator versions 1.6 and 1.8 lay them out, -//! plus the container hash that D3D12 checks. +//! program (`DXIL`), laid out as validator version 1.6 lays them out, plus +//! the container hash that D3D12 checks. /// One signature element: one row (D3D12 links stages by semantic). #[derive(Debug, Clone, PartialEq, Eq)] @@ -25,32 +25,6 @@ pub(crate) struct SigElement { } impl SigElement { - /// Canonical DXIL semantic name for system values (`kind != 0`), matching - /// what `dxil.dll` writes when regenerating `ISG1`/`OSG1` during validation. - fn canonical_name(&self) -> &str { - match self.kind { - 1 => "SV_VertexID", - 2 => "SV_InstanceID", - 3 => "SV_Position", - 4 => "SV_RenderTargetArrayIndex", - 5 => "SV_ViewportArrayIndex", - 6 => "SV_ClipDistance", - 7 => "SV_CullDistance", - 10 => "SV_PrimitiveID", - 12 => "SV_SampleIndex", - 13 => "SV_IsFrontFace", - 14 => "SV_Coverage", - 15 => "SV_InnerCoverage", - 16 => "SV_Target", - 17 => "SV_Depth", - 18 => "SV_DepthLessEqual", - 19 => "SV_DepthGreaterEqual", - 20 => "SV_StencilRef", - 30 => "SV_CullPrimitive", - _ => &self.name, - } - } - fn system_value(&self) -> u32 { match self.kind { 1 => 6, // vertex id @@ -98,9 +72,7 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { // Validator 1.6 writes one name per element in element order, repeats // included, except that system values share theirs (it keys names by // the semantic's string, which is one static string per system value); - // the rows sorted by register (unallocated last), then by name offset, - // not column (its `sort_sig`): rows of one register keep element order, - // apart from system values. + // the rows sorted by register (unallocated last). let mut offsets: Vec = Vec::new(); let mut next = 8 + 32 * elements.len() as u32; let mut names = Vec::new(); @@ -111,15 +83,14 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { match shared { Some(j) => offsets.push(offsets[j]), None => { - let name = e.canonical_name(); offsets.push(next); - next += name.len() as u32 + 1; - names.push(name); + next += e.name.len() as u32 + 1; + names.push(&e.name); } } } let mut order: Vec = (0..elements.len()).collect(); - order.sort_by_key(|&i| elements[i].row.unwrap_or(u32::MAX)); + order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), elements[i].col)); for i in order { let (e, offset) = (&elements[i], offsets[i]); let used = e.usage << e.col; @@ -190,11 +161,9 @@ pub(crate) struct Psv<'a> { /// Compute: thread-group size and required wave size. pub threads: [u32; 3], pub wave_size: Option, - /// Validator 1.8: runtime info 3 and the entry-point name. - pub validator18: bool, } -/// `PSV0` with runtime info version 2, or 3 for validator 1.8. +/// `PSV0` with runtime info version 2 (validator 1.6). pub(crate) fn psv(p: &Psv) -> Vec { let vectors = |els: &[SigElement]| { els.iter() @@ -210,9 +179,8 @@ pub(crate) fn psv(p: &Psv) -> Vec { out.extend(v.to_le_bytes()); } }; - let info_size = if p.validator18 { 52 } else { 48 }; - u32s(&mut out, &[info_size]); - let mut info = [0u8; 52]; + u32s(&mut out, &[48]); + let mut info = [0u8; 48]; info[0] = u8::from(p.flag); if p.stage == 0 { // PSInfo.SampleFrequency: an input interpolated per sample, or the @@ -242,10 +210,6 @@ pub(crate) fn psv(p: &Psv) -> Vec { info[27] = mesh.topology; info[30] = p.prims.len() as u8; } - if p.validator18 { - // Runtime info 3 names the entry point at offset 1 in the strings. - info[48..52].copy_from_slice(&1u32.to_le_bytes()); - } if let Some(max_vertices) = p.geometry { // Input primitive (3: triangles), output topology (5: triangle // strips), stream mask, position written; the vertex maximum. @@ -255,7 +219,7 @@ pub(crate) fn psv(p: &Psv) -> Vec { info[12] = u8::from(p.flag); info[26..28].copy_from_slice(&(max_vertices as u16).to_le_bytes()); } - out.extend(&info[..info_size as usize]); + out.extend(info); u32s(&mut out, &[p.bindings.len() as u32]); if !p.bindings.is_empty() { u32s(&mut out, &[24]); @@ -266,21 +230,20 @@ pub(crate) fn psv(p: &Psv) -> Vec { ); } } - // The optional entry point and arbitrary semantics (system values use ""), - // then indices. - let mut strings = if p.validator18 { - b"\0main\0".to_vec() - } else { - vec![0] - }; + // Names of arbitrary semantics (system values use ""), then indices. + let mut strings = vec![0u8]; let mut indices: Vec = Vec::new(); let mut elements = Vec::new(); for e in p.inputs.iter().chain(p.outputs).chain(p.prims) { let name = if e.kind == 0 { - let at = strings.len(); - strings.extend(e.name.bytes()); - strings.push(0); - at + let needle: Vec = e.name.bytes().chain([0]).collect(); + match find(&strings, &needle) { + Some(at) => at, + None => { + strings.extend(&needle); + strings.len() - needle.len() + } + } } else { 0 }; @@ -339,6 +302,10 @@ pub(crate) fn psv(p: &Psv) -> Vec { out } +fn find(hay: &[u8], needle: &[u8]) -> Option { + hay.windows(needle.len()).position(|w| w == needle) +} + /// The container: parts in order, hashed. pub(crate) fn build(parts: &[(&[u8; 4], &[u8])]) -> Vec { let table = 0x20 + 4 * parts.len(); @@ -431,46 +398,8 @@ fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) { #[cfg(test)] mod tests { - use super::super::shader::Mesh; use super::*; - fn words(bytes: &[u8]) -> Vec { - let (words, remainder) = bytes.as_chunks::<4>(); - assert!(remainder.is_empty()); - words.iter().copied().map(u32::from_le_bytes).collect() - } - - fn element(name: &str, row: Option, col: u8, cols: u8) -> SigElement { - SigElement { - name: name.into(), - index: 0, - kind: 0, - comp: 9, - interp: 0, - row, - col, - cols, - usage: 1, - half: false, - } - } - - fn empty_psv(stage: u8) -> Psv<'static> { - Psv { - stage, - flag: false, - validator18: false, - inputs: &[], - outputs: &[], - prims: &[], - mesh: None, - bindings: &[], - threads: [0; 3], - wave_size: None, - geometry: None, - } - } - #[test] fn md5_core_matches_the_standard() { // Standard MD5 of "abc" with standard padding, through md5_block. @@ -487,403 +416,4 @@ mod tests { .collect(); assert_eq!(hex, "900150983cd24fb0d6963f7d28e17f72"); } - #[test] - fn hash_matches_synthetic_vectors_at_padding_boundaries() { - // Calculated independently by applying MD5 compression to the - // retail-format padded byte sequences 0, 1, ..., len - 1. - let vectors = [ - ( - 0, - [ - 0x14, 0x0d, 0x60, 0xf6, 0xb7, 0x75, 0xe2, 0xba, 0x4e, 0x4a, 0xbe, 0xd4, 0x01, - 0xb2, 0xe9, 0xa1, - ], - ), - ( - 55, - [ - 0x84, 0x2e, 0x55, 0x53, 0x4b, 0xa9, 0x3d, 0xaa, 0x93, 0xe9, 0x4b, 0xd5, 0xaf, - 0x9b, 0x0c, 0x03, - ], - ), - ( - 56, - [ - 0x00, 0xf9, 0xcc, 0x96, 0x4f, 0xf2, 0xec, 0x81, 0x95, 0x9d, 0x4a, 0x3f, 0x09, - 0x2c, 0xe6, 0x3f, - ], - ), - ( - 63, - [ - 0x44, 0x00, 0xd4, 0x28, 0xa4, 0x1d, 0x0e, 0x75, 0xdc, 0x98, 0xb9, 0x36, 0x69, - 0x3f, 0x7b, 0xfb, - ], - ), - ( - 64, - [ - 0xf4, 0x2e, 0xb0, 0x6c, 0xa9, 0x21, 0xc8, 0x78, 0xe4, 0x35, 0xe3, 0xb8, 0xd4, - 0xf9, 0x2b, 0x13, - ], - ), - ( - 119, - [ - 0xba, 0x3a, 0x67, 0xec, 0xd4, 0x64, 0x1c, 0xe4, 0xed, 0x08, 0xf2, 0x91, 0x89, - 0x6e, 0x1b, 0xc6, - ], - ), - ( - 120, - [ - 0x88, 0x2f, 0xce, 0x4f, 0x4c, 0x95, 0x19, 0x43, 0x92, 0xe7, 0xad, 0xef, 0xd5, - 0x3f, 0xe3, 0x43, - ], - ), - ]; - let data: Vec = (0..120).collect(); - for (len, expected) in vectors { - assert_eq!(hash(&data[..len]), expected, "length {len}"); - } - } - - #[test] - fn empty_container_has_only_the_signed_header() { - let bytes = build(&[]); - assert_eq!(&bytes[..4], b"DXBC"); - assert_eq!(&bytes[20..], &[1, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0]); - assert_eq!( - words(&bytes[4..20]), - [0x4c07_86fe, 0xe9c2_2f40, 0xa34f_0f0e, 0xc05b_06bf] - ); - } - - #[test] - fn container_offsets_are_contiguous_after_an_unpadded_signature() { - let bytes = build(&[ - (b"ISG1", &[0x11, 0x22, 0x33]), - (b"OSG1", &[]), - (b"PRIV", &[]), - ]); - assert_eq!(&bytes[..4], b"DXBC"); - assert_eq!(words(&bytes[20..44]), [1, 71, 3, 44, 55, 63]); - assert_eq!(&bytes[44..55], b"ISG1\x03\0\0\0\x11\x22\x33"); - assert_eq!(&bytes[55..63], b"OSG1\0\0\0\0"); - assert_eq!(&bytes[63..], b"PRIV\0\0\0\0"); - assert_eq!( - words(&bytes[4..20]), - [0xe8e8_9b79, 0x8857_cd6c, 0xf7ec_2ab3, 0x137d_e43d] - ); - } - - #[test] - fn signature_sorts_rows_and_preserves_legacy_name_offsets_and_masks() { - assert_eq!(words(&signature(&[], true)), [0, 8]); - let elements = [ - SigElement { - index: 7, - ..element("COLOR", Some(1), 2, 2) - }, - SigElement { - index: 1, - kind: 16, - usage: 15, - ..element("SV_Target", Some(3), 0, 4) - }, - SigElement { - index: 8, - comp: 4, - usage: 2, - ..element("COLOR", Some(1), 0, 2) - }, - SigElement { - kind: 16, - usage: 15, - ..element("SV_Target", Some(2), 0, 4) - }, - SigElement { - kind: 17, - ..element("SV_Depth", None, 0, 1) - }, - ]; - let input = signature(&elements, true); - let output = signature(&elements, false); - let rows = [ - [0, 168, 7, 0, 3, 1, 0x040c, 0], - [0, 184, 8, 0, 2, 1, 0x0203, 0], - [0, 174, 0, 64, 3, 2, 0x0f0f, 0], - [0, 174, 1, 64, 3, 3, 0x0f0f, 0], - [0, 190, 0, 65, 3, u32::MAX, 0x0101, 0], - ]; - assert_eq!(words(&input[..8]), [5, 8]); - assert_eq!(words(&output[..8]), [5, 8]); - assert_eq!(&input[168..], b"COLOR\0SV_Target\0COLOR\0SV_Depth\0"); - assert_eq!(&output[168..], &input[168..]); - for (i, (row, output_mask)) in rows.into_iter().zip([0x0b, 0x0d, 0, 0, 0x0e]).enumerate() { - let start = 8 + 32 * i; - assert_eq!(words(&input[start..start + 32]), row); - let mut expected = row; - expected[6] = (row[6] & 0xff) | (output_mask << 8); - assert_eq!(words(&output[start..start + 32]), expected); - } - } - - #[test] - fn compute_psv_contains_thread_and_wave_sizes_with_empty_tables() { - let bytes = psv(&Psv { - threads: [8, 4, 2], - wave_size: Some(32), - ..empty_psv(5) - }); - assert_eq!( - words(&bytes), - [48, 0, 0, 0, 0, 32, 32, 5, 0, 0, 8, 4, 2, 0, 4, 0, 0] - ); - } - - #[test] - fn pixel_sample_frequency_depends_on_sample_interpolation_or_semantic() { - for (interp, kind, expected) in [(5, 0, 0), (6, 0, 1), (7, 0, 1), (0, 12, 1)] { - let inputs = [SigElement { - interp, - kind, - ..element("UV", Some(0), 0, 1) - }]; - let bytes = psv(&Psv { - flag: true, - inputs: &inputs, - ..empty_psv(0) - }); - assert_eq!(&bytes[4..8], &[1, expected, 0, 0]); - assert_eq!(words(&bytes[20..28]), [0, u32::MAX]); - } - } - - #[test] - fn vertex_psv_encodes_bindings_tables_and_cross_word_dependencies() { - let inputs = [SigElement { - index: 3, - interp: 2, - ..element("COLOR", Some(0), 1, 2) - }]; - let outputs = [SigElement { - index: 3, - ..element("OR", Some(8), 1, 1) - }]; - let bytes = psv(&Psv { - inputs: &inputs, - outputs: &outputs, - bindings: &[ - Binding { - kind: 1, - space: 6, - register: 9, - dxil_kind: 14, - }, - Binding { - kind: 2, - space: 7, - register: 2, - dxil_kind: 13, - }, - ], - ..empty_psv(1) - }); - assert_eq!(&bytes[28..40], &[1, 0, 0, 0, 1, 1, 0, 1, 9, 0, 0, 0]); - assert_eq!( - words(&bytes[52..112]), - [2, 24, 1, 6, 9, 9, 14, 0, 2, 7, 2, 2, 13, 0, 12] - ); - assert_eq!(&bytes[112..124], b"\0COLOR\0OR\0\0\0"); - assert_eq!(words(&bytes[124..136]), [1, 3, 16]); - assert_eq!( - words(&bytes[136..168]), - [1, 0, 0x0052_0001, 0x0203, 7, 0, 0x0051_0801, 3] - ); - assert_eq!( - words(&bytes[168..]), - [u32::MAX, 3, u32::MAX, 3, u32::MAX, 3, 0, 0] - ); - } - - #[test] - fn mesh_psv_encodes_shared_memory_and_primitive_outputs() { - let outputs = [SigElement { - kind: 3, - ..element("SV_Position", Some(0), 0, 4) - }]; - let prims = [SigElement { - kind: 30, - comp: 1, - index: 2, - ..element("SV_CullPrimitive", Some(1), 3, 1) - }]; - let bytes = psv(&Psv { - outputs: &outputs, - prims: &prims, - mesh: Some(( - Mesh { - max_vertices: 64, - max_primitives: 127, - topology: 2, - }, - 1024, - )), - threads: [32, 1, 1], - ..empty_psv(13) - }); - assert_eq!(words(&bytes[..20]), [48, 1024, 0, 0, 0x007f_0040]); - assert_eq!(&bytes[28..40], &[13, 0, 2, 2, 0, 1, 1, 0, 1, 0, 0, 0]); - assert_eq!( - words(&bytes[40..]), - [ - 32, - 1, - 1, - 0, - 4, - 0, - 2, - 0, - 2, - 16, - 0, - 0, - 0x0344_0001, - 3, - 0, - 1, - 0x1e71_0101, - 1 - ] - ); - } - - #[test] - fn psv_writes_distinct_string_entries_for_repeated_arbitrary_semantics() { - let el = |name: &str, index: u32, kind: u8, row: u32| SigElement { - name: name.into(), - index, - kind, - comp: 9, - interp: 2, - row: Some(row), - col: 0, - cols: 4, - usage: 0xF, - half: false, - }; - let inputs = [ - el("SV_Position", 0, 3, 0), - el("TEXCOORD", 0, 0, 1), - el("TEXCOORD", 1, 0, 2), - ]; - let bytes = psv(&Psv { - stage: 0, - flag: false, - inputs: &inputs, - outputs: &[], - prims: &[], - mesh: None, - bindings: &[], - threads: [0; 3], - wave_size: None, - validator18: false, - geometry: None, - }); - let u32_at = |off: usize| u32::from_le_bytes(bytes[off..off + 4].try_into().unwrap()); - let info_sz = u32_at(0) as usize; - let mut pos = 4 + info_sz; - assert_eq!(u32_at(pos), 0); // 0 bindings - pos += 4; - let str_len = u32_at(pos) as usize; - pos += 4; - let strings = &bytes[pos..pos + str_len]; - // Leading empty string plus two distinct "TEXCOORD\0" entries. - assert!(strings.starts_with(b"\0TEXCOORD\0TEXCOORD\0")); - pos += str_len; - let idx_cnt = u32_at(pos) as usize; - pos += 4 + idx_cnt * 4; - let el_sz = u32_at(pos) as usize; - assert_eq!(el_sz, 16); - pos += 4; - let name0 = u32_at(pos); - let name1 = u32_at(pos + el_sz); - let name2 = u32_at(pos + 2 * el_sz); - assert_eq!(name0, 0); - assert_eq!(name1, 1); - assert_eq!(name2, 10); - } - - #[test] - fn signature_sorts_by_row_only_preserving_co_packed_order() { - let el = |name: &str, row: u32, col: u8, cols: u8| SigElement { - name: name.into(), - index: 0, - kind: 0, - comp: 9, - interp: 2, - row: Some(row), - col, - cols, - usage: (1 << cols) - 1, - half: false, - }; - let bytes = signature( - &[ - el("SECOND_ROW", 1, 0, 4), - el("HI_HALF", 0, 2, 2), - el("LO_HALF", 0, 0, 2), - ], - true, - ); - let u32_at = |off: usize| u32::from_le_bytes(bytes[off..off + 4].try_into().unwrap()); - assert_eq!(u32_at(0), 3); - let row_name = |i: usize| { - let name_off = u32_at(8 + i * 32 + 4) as usize; - let end = bytes[name_off..].iter().position(|&b| b == 0).unwrap(); - std::str::from_utf8(&bytes[name_off..name_off + end]).unwrap() - }; - assert_eq!(row_name(0), "HI_HALF"); - assert_eq!(row_name(1), "LO_HALF"); - assert_eq!(row_name(2), "SECOND_ROW"); - } - - #[test] - fn rows_of_one_register_keep_element_order_not_column_order() { - let element = |name: &str, index, kind, row, col, cols| SigElement { - name: name.into(), - index, - kind, - comp: 9, - interp: if kind == 0 { 2 } else { 4 }, - row: Some(row), - col, - cols, - usage: (1 << cols) - 1, - half: false, - }; - // As a vertex program declares them: a w channel before the xyz of - // the same register. - let elements = [ - element("SV_Position", 0, 3, 0, 0, 4), - element("TEXCOORD", 3, 0, 1, 3, 1), - element("NORMAL", 0, 0, 1, 0, 3), - ]; - let part = signature(&elements, false); - let rows: Vec<(u32, u32)> = (0..3) - .map(|r| { - let word = |k: usize| { - let at = 8 + 32 * r + 4 * k; - u32::from_le_bytes(part[at..at + 4].try_into().unwrap()) - }; - // Semantic index and register. - (word(2), word(5)) - }) - .collect(); - // Register order, then name offset (element order here), as the - // validator writes them: TEXCOORD3 before NORMAL0 in register 1. - assert_eq!(rows, [(0, 0), (3, 1), (0, 1)]); - } } diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index fdc02aa..4727b92 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -141,7 +141,7 @@ const CASES: &[(&str, &str)] = &[ }"#, ), // 16-bit outputs and inputs (one value per dword with the 2020 - // compiler; Grand Theft Auto VI's two per dword cannot be compiled + // compiler; the title's two per dword cannot be compiled // here) and the front face. ( "16-bit varyings and front face", @@ -354,7 +354,7 @@ const CS_CASES: &[(&str, &str)] = &[ uint4(w * 7 + h, l + asuint(r), n * 5 + ns * 3 + st, b + raw.Load(4 * (i & 31)))); }"#, ), - // Typed loads (`tbuffer_load_format_*`, Grand Theft Auto VI's vertex + // Typed loads (`tbuffer_load_format_*`, the title's vertex // fetch) convert by the format the instruction names: the PC reads the // same bytes through typed views in those formats. Channels past the // format's read (0, 0, 0, 1); a byte format at unaligned offsets. @@ -587,7 +587,7 @@ const MS_CASES: &[(&str, u32, &str)] = &[ } }"#, ), - // Two waves per group, as Grand Theft Auto VI's mesh programs run: the + // Two waves per group, as the title's mesh programs run: the // second wave's lanes are threads 64-127. ( "two waves", @@ -605,7 +605,7 @@ const MS_CASES: &[(&str, u32, &str)] = &[ tris[i] = i & 1 ? uint3(c + 1, c + 10, c + 9) : uint3(c, c + 1, c + 9); }"#, ), - // Quad reads (DPP quad permutations on the console; Grand Theft Auto VI's + // Quad reads (DPP quad permutations on the console; the title's // tessellating mesh programs swizzle within quads too). ( "quad reads", diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 7dd8295..8f5407a 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -85,18 +85,6 @@ impl Host { let adapter: IDXGIAdapter = factory.EnumWarpAdapter().map_err(err)?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; } else { - // A machine without a graphics card gives the software - // adapter as its default one (a hosted test runner): that - // is no hardware device, and the tests that ask for one - // skip it, as they do where there is none. - let factory: IDXGIFactory4 = - CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; - if let Ok(first) = factory.EnumAdapters1(0) - && let Ok(desc) = first.GetDesc1() - && desc.Flags & 2 != 0 - { - return Err("the default adapter is a software adapter".to_owned()); - } D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; // A machine without a graphics card gives the software // adapter as its default device (a hosted test runner, @@ -106,11 +94,9 @@ impl Host { if let Some(made) = &device { let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; - if let Ok(adapter) = - factory.EnumAdapterByLuid::(made.GetAdapterLuid()) + if let Ok(adapter) = factory.EnumAdapterByLuid::(made.GetAdapterLuid()) && let Ok(desc) = adapter.GetDesc1() - && (desc.Flags & 2 != 0 - || (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)) + && (desc.Flags & 2 != 0 || (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)) { return Err("the default device is the software adapter".to_owned()); } @@ -157,14 +143,6 @@ impl Host { &self, stages: &[(&HostShader, D3D12_SHADER_VISIBILITY)], ) -> Result { - self.root_signature_with_extra(stages, &[]).map(|(r, _)| r) - } - - fn root_signature_with_extra( - &self, - stages: &[(&HostShader, D3D12_SHADER_VISIBILITY)], - extra: &[D3D12_ROOT_PARAMETER1], - ) -> Result<(ID3D12RootSignature, u32), String> { let mut params: Vec = stages .iter() .map(|&(s, vis)| D3D12_ROOT_PARAMETER1 { @@ -207,33 +185,6 @@ impl Host { ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); } - // The address map, then the descriptor words, come last. - for (wanted, space) in [ - ( - stages.iter().any(|(s, _)| s.address_map), - super::ADDRESS_MAP_SPACE, - ), - ( - stages.iter().any(|(s, _)| s.descriptor_words), - super::DESCRIPTOR_WORDS_SPACE, - ), - ] { - if wanted { - params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR1 { - ShaderRegister: 0, - RegisterSpace: space, - Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }); - } - } - let extra_base = params.len() as u32; - params.extend_from_slice(extra); let mut samplers = Vec::new(); for &(s, vis) in stages { for (n, d) in s.static_samplers.iter().enumerate() { @@ -270,7 +221,7 @@ impl Host { }, }; // SAFETY: the description points at live arrays. - let root = unsafe { + unsafe { let mut blob = None; let mut error = None; D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) @@ -280,9 +231,8 @@ impl Host { blob.GetBufferPointer().cast::(), blob.GetBufferSize(), ); - self.device.CreateRootSignature(0, bytes).map_err(err)? - }; - Ok((root, extra_base)) + self.device.CreateRootSignature(0, bytes).map_err(err) + } } /// A compute pipeline; user data is root parameter 0. @@ -330,10 +280,7 @@ impl Host { let message = buffer.as_mut_ptr().cast::(); if queue.GetMessage(i, Some(message), &mut len).is_ok() { let m = &*message; - let bytes = std::slice::from_raw_parts( - m.pDescription, - m.DescriptionByteLength.saturating_sub(1), - ); + let bytes = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength.saturating_sub(1)); text.push_str(" | "); text.push_str(&String::from_utf8_lossy(bytes)); } @@ -406,11 +353,9 @@ impl Host { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len(), }, - GS: gs.map_or(D3D12_SHADER_BYTECODE::default(), |gs| { - D3D12_SHADER_BYTECODE { - pShaderBytecode: gs.as_ptr().cast(), - BytecodeLength: gs.len(), - } + GS: gs.map_or(D3D12_SHADER_BYTECODE::default(), |gs| D3D12_SHADER_BYTECODE { + pShaderBytecode: gs.as_ptr().cast(), + BytecodeLength: gs.len(), }), SampleMask: u32::MAX, RasterizerState: D3D12_RASTERIZER_DESC { @@ -562,113 +507,6 @@ impl Host { // SAFETY: the stream points at live data and outlives the call. unsafe { device.CreatePipelineState(&desc) }.map_err(err) } - - /// Whether the host supports hardware mesh shaders at shader model 6.6. - pub fn mesh_shaders(&self) -> bool { - let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); - // SAFETY: writes into `options` of its exact size. - unsafe { - self.device - .CheckFeatureSupport( - D3D12_FEATURE_D3D12_OPTIONS7, - (&raw mut options).cast(), - size_of_val(&options) as u32, - ) - .is_ok() - && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED - } - } - - /// Dual compute + unpack vertex/pixel pipelines for an emulated mesh shader. - pub fn emulated_mesh_pipelines( - &self, - ms: &HostShader, - ps: &HostShader, - ) -> Result { - let emu = ms - .mesh_emu - .as_ref() - .ok_or("mesh shader was not translated in emulation mode")?; - let mut cs_extra = vec![D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR1 { - ShaderRegister: 0, - RegisterSpace: super::MESH_EMU_SPACE, - Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }]; - if emu.reads_group_id { - cs_extra.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Constants: D3D12_ROOT_CONSTANTS { - ShaderRegister: 0, - RegisterSpace: super::MESH_EMU_SPACE, - Num32BitValues: 4, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }); - cs_extra.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR1 { - ShaderRegister: 0, - RegisterSpace: super::MESH_EMU_SPACE, - Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }); - } - let (cs_root, cs_base) = - self.root_signature_with_extra(&[(ms, D3D12_SHADER_VISIBILITY_ALL)], &cs_extra)?; - let cs_pso = self.compute_pipeline_with(&cs_root, &ms.dxil)?; - - let unpack_vs = - super::unpack_vertex_shader(emu, Some(&ps.dxil)).map_err(|e| e.to_string())?; - let (gfx_root, gfx_srv_param) = self.root_signature_with_extra( - &[(ps, D3D12_SHADER_VISIBILITY_PIXEL)], - &[D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR1 { - ShaderRegister: 0, - RegisterSpace: super::MESH_EMU_SPACE, - Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_VERTEX, - }], - )?; - let gfx_pso = self.pipeline_with(&gfx_root, &unpack_vs, &ps.dxil)?; - - Ok(EmulatedMeshPipelines { - cs_root, - cs_pso, - gfx_root, - gfx_pso, - cs_uav_param: cs_base, - cs_cbv_param: emu.reads_group_id.then_some(cs_base + 1), - cs_srv_param: emu.reads_group_id.then_some(cs_base + 2), - gfx_srv_param, - }) - } -} - -/// Compute + unpack graphics pipelines built for an emulated mesh shader. -pub struct EmulatedMeshPipelines { - pub cs_root: ID3D12RootSignature, - pub cs_pso: ID3D12PipelineState, - pub gfx_root: ID3D12RootSignature, - pub gfx_pso: ID3D12PipelineState, - pub cs_uav_param: u32, - pub cs_cbv_param: Option, - pub cs_srv_param: Option, - pub gfx_srv_param: u32, } /// A vertex shader that feeds `ps`'s inputs (zeros) and a position. @@ -760,11 +598,8 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), - address_map: false, - descriptor_words: false, root_uavs: Vec::new(), root_indexed_views: Vec::new(), - mesh_emu: None, } } @@ -1151,8 +986,6 @@ pub enum View<'a> { Cube(u32, &'a [[f32; 4]]), /// A raw buffer UAV of this many dwords, zeroed. RawUav(u32), - /// A raw buffer UAV holding these dwords (read back like `RawUav`). - RawData(&'a [u32]), /// An RGBA32F texture UAV (width, height), zeroed. TextureUav(u32, u32), /// An R32_UINT texture UAV (width, height), zeroed (atomics). @@ -1391,7 +1224,7 @@ impl Host { ); keep.push(tex); } - View::RawUav(_) | View::HalfUav(_) | View::RawData(_) => { + View::RawUav(_) | View::HalfUav(_) => { // (dwords, format, elements, flags) let (n, format, elements, flags) = match *v { View::HalfUav(e) => ( @@ -1403,10 +1236,6 @@ impl Host { View::RawUav(n) => { (n, DXGI_FORMAT_R32_TYPELESS, n, D3D12_BUFFER_UAV_FLAG_RAW) } - View::RawData(d) => { - let n = d.len() as u32; - (n, DXGI_FORMAT_R32_TYPELESS, n, D3D12_BUFFER_UAV_FLAG_RAW) - } _ => unreachable!(), }; let bytes = u64::from(n) * 4; @@ -1427,17 +1256,6 @@ impl Host { }, }; dev.CreateUnorderedAccessView(&b, None, Some(&desc), at); - if let View::RawData(d) = *v { - // The copy promotes the buffer to a copy target. - let up = upload(d)?; - list.CopyBufferRegion(&b, 0, &up, 0, bytes); - list.ResourceBarrier(&[transition( - &b, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - )]); - keep.push(up); - } let rb = make( D3D12_HEAP_TYPE_READBACK, &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), @@ -1633,313 +1451,3 @@ impl Host { } } } - -/// Bindings for [`Host::draw_emulated_mesh`]. -#[cfg(test)] -pub struct EmulatedMeshDraw<'a> { - pub cs_roots: Vec<(u32, Root)>, - pub ps_roots: Vec<(u32, Root)>, - pub size: (u32, u32), - pub groups: u32, - pub max_primitives: u32, - pub group_bytes: u32, - pub base_group: u32, - pub slot_map: Option<&'a [u32]>, -} - -#[cfg(test)] -impl Host { - /// Runs an emulated mesh shader (`cs_6_6`) followed by its unpack `vs_6_6` - /// + `ps_6_6` draw into a cleared RGBA32F render target and returns texels. - pub fn draw_emulated_mesh( - &self, - pipes: &EmulatedMeshPipelines, - d: &EmulatedMeshDraw, - ) -> Result, String> { - let dev = &self.device; - let (w, h) = d.size; - // SAFETY: D3D12 calls with descriptions that outlive them; resources - // remain alive until the fence reports GPU completion. - unsafe { - let queue: ID3D12CommandQueue = dev - .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { - Type: D3D12_COMMAND_LIST_TYPE_DIRECT, - ..Default::default() - }) - .map_err(err)?; - let alloc: ID3D12CommandAllocator = dev - .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) - .map_err(err)?; - let list: ID3D12GraphicsCommandList = dev - .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pipes.cs_pso) - .map_err(err)?; - let tex_desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width: u64::from(w), - Height: h, - DepthOrArraySize: 1, - MipLevels: 1, - Format: DXGI_FORMAT_R32G32B32A32_FLOAT, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, - ..Default::default() - }; - let buf_desc = |size: u64, flags| D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size.max(4), - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: flags, - ..Default::default() - }; - let make = |heap: D3D12_HEAP_TYPE, - desc: &D3D12_RESOURCE_DESC, - state, - clear: Option<&D3D12_CLEAR_VALUE>| { - let mut r: Option = None; - dev.CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { - Type: heap, - ..Default::default() - }, - D3D12_HEAP_FLAG_NONE, - desc, - state, - clear.map(|c| c as *const _), - &mut r, - ) - .map_err(err)?; - r.ok_or_else(|| "no resource".to_string()) - }; - let target = make( - D3D12_HEAP_TYPE_DEFAULT, - &tex_desc, - D3D12_RESOURCE_STATE_RENDER_TARGET, - Some(&D3D12_CLEAR_VALUE { - Format: DXGI_FORMAT_R32G32B32A32_FLOAT, - Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0; 4] }, - }), - )?; - let rtv_heap: ID3D12DescriptorHeap = dev - .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, - NumDescriptors: 1, - ..Default::default() - }) - .map_err(err)?; - let rtv = rtv_heap.GetCPUDescriptorHandleForHeapStart(); - dev.CreateRenderTargetView(&target, None, rtv); - let views: ID3D12DescriptorHeap = dev - .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - NumDescriptors: 1, - Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, - ..Default::default() - }) - .map_err(err)?; - let sampler_heap: ID3D12DescriptorHeap = dev - .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, - NumDescriptors: 1, - Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, - ..Default::default() - }) - .map_err(err)?; - - let out_bytes = (u64::from(d.groups.max(1)) * u64::from(d.group_bytes.max(4))).max(256); - let output = make( - D3D12_HEAP_TYPE_DEFAULT, - &buf_desc(out_bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - None, - )?; - let map_words = d.slot_map.map_or(1, |m| m.len().max(1)); - let map_bytes = ((map_words * 4).next_multiple_of(256)) as u64; - let slot_map_buf = make( - D3D12_HEAP_TYPE_UPLOAD, - &buf_desc(map_bytes, D3D12_RESOURCE_FLAG_NONE), - D3D12_RESOURCE_STATE_GENERIC_READ, - None, - )?; - let mut mp = std::ptr::null_mut(); - slot_map_buf.Map(0, None, Some(&mut mp)).map_err(err)?; - std::ptr::write_bytes(mp, 0, map_bytes as usize); - if let Some(map) = d.slot_map { - std::ptr::copy_nonoverlapping(map.as_ptr(), mp.cast::(), map.len()); - } - slot_map_buf.Unmap(0, None); - - let mut keep = Vec::new(); - let upload_dwords = |data: &[u32]| -> Result { - let bytes = (data.len() * 4).next_multiple_of(256) as u64; - let b = make( - D3D12_HEAP_TYPE_UPLOAD, - &buf_desc(bytes, D3D12_RESOURCE_FLAG_NONE), - D3D12_RESOURCE_STATE_GENERIC_READ, - None, - )?; - let mut p = std::ptr::null_mut(); - b.Map(0, None, Some(&mut p)).map_err(err)?; - std::ptr::copy_nonoverlapping(data.as_ptr(), p.cast::(), data.len()); - b.Unmap(0, None); - Ok(b) - }; - - list.SetDescriptorHeaps(&[Some(views.clone()), Some(sampler_heap.clone())]); - list.SetComputeRootSignature(&pipes.cs_root); - for (param, arg) in &d.cs_roots { - match arg { - Root::Constants(data) => list.SetComputeRoot32BitConstants( - *param, - data.len() as u32, - data.as_ptr().cast(), - 0, - ), - Root::View { srv, data } => { - let b = upload_dwords(data)?; - let va = b.GetGPUVirtualAddress(); - if *srv { - list.SetComputeRootShaderResourceView(*param, va); - } else { - list.SetComputeRootConstantBufferView(*param, va); - } - keep.push(b); - } - Root::Table { .. } => return Err("descriptor tables not supported here".into()), - } - } - list.SetComputeRootUnorderedAccessView( - pipes.cs_uav_param, - output.GetGPUVirtualAddress(), - ); - if let Some(p) = pipes.cs_cbv_param { - let c = [d.base_group, 0, 0, 0]; - list.SetComputeRoot32BitConstants(p, 4, c.as_ptr().cast(), 0); - } - if let Some(p) = pipes.cs_srv_param { - list.SetComputeRootShaderResourceView(p, slot_map_buf.GetGPUVirtualAddress()); - } - list.Dispatch(d.groups, 1, 1); - - list.ResourceBarrier(&[transition( - &output, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - )]); - list.SetPipelineState(&pipes.gfx_pso); - list.SetGraphicsRootSignature(&pipes.gfx_root); - for (param, arg) in &d.ps_roots { - match arg { - Root::Constants(data) => list.SetGraphicsRoot32BitConstants( - *param, - data.len() as u32, - data.as_ptr().cast(), - 0, - ), - Root::View { srv, data } => { - let b = upload_dwords(data)?; - let va = b.GetGPUVirtualAddress(); - if *srv { - list.SetGraphicsRootShaderResourceView(*param, va); - } else { - list.SetGraphicsRootConstantBufferView(*param, va); - } - keep.push(b); - } - Root::Table { .. } => return Err("descriptor tables not supported here".into()), - } - } - list.SetGraphicsRootShaderResourceView( - pipes.gfx_srv_param, - output.GetGPUVirtualAddress(), - ); - list.ClearRenderTargetView(rtv, &[0.0; 4], None); - list.OMSetRenderTargets(1, Some(&rtv), false, None); - list.RSSetViewports(&[D3D12_VIEWPORT { - Width: w as f32, - Height: h as f32, - MaxDepth: 1.0, - ..Default::default() - }]); - list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { - right: w as i32, - bottom: h as i32, - ..Default::default() - }]); - list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - list.DrawInstanced(d.groups * d.max_primitives * 3, 1, 0, 0); - - list.ResourceBarrier(&[transition( - &target, - D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATE_COPY_SOURCE, - )]); - let pitch = (w as usize * 16).next_multiple_of(256); - let readback = make( - D3D12_HEAP_TYPE_READBACK, - &buf_desc((pitch * h as usize) as u64, D3D12_RESOURCE_FLAG_NONE), - D3D12_RESOURCE_STATE_COPY_DEST, - None, - )?; - let dst = D3D12_TEXTURE_COPY_LOCATION { - pResource: std::mem::transmute_copy(&readback), - Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { - Offset: 0, - Footprint: D3D12_SUBRESOURCE_FOOTPRINT { - Format: DXGI_FORMAT_R32G32B32A32_FLOAT, - Width: w, - Height: h, - Depth: 1, - RowPitch: pitch as u32, - }, - }, - }, - }; - let src = D3D12_TEXTURE_COPY_LOCATION { - pResource: std::mem::transmute_copy(&target), - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: 0, - }, - }; - list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); - list.Close().map_err(err)?; - queue.ExecuteCommandLists(&[Some(list.cast().map_err(err)?)]); - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?; - queue.Signal(&fence, 1).map_err(err)?; - while fence.GetCompletedValue() < 1 { - if let Err(e) = dev.GetDeviceRemovedReason() { - return Err(format!("device removed: {}", err(e))); - } - std::thread::yield_now(); - } - if let Err(e) = dev.GetDeviceRemovedReason() { - return Err(format!("device removed: {}", err(e))); - } - let mut p = std::ptr::null_mut(); - readback.Map(0, None, Some(&mut p)).map_err(err)?; - let mut out = Vec::with_capacity((w * h) as usize); - for y in 0..h as usize { - let row = std::slice::from_raw_parts( - p.cast::().add(y * pitch).cast::<[f32; 4]>(), - w as usize, - ); - out.extend_from_slice(row); - } - readback.Unmap(0, None); - drop(keep); - Ok(out) - } - } -} diff --git a/crates/victory-shader/src/emit/image_atomic_tests.rs b/crates/victory-shader/src/emit/image_atomic_tests.rs deleted file mode 100644 index 6f463e3..0000000 --- a/crates/victory-shader/src/emit/image_atomic_tests.rs +++ /dev/null @@ -1,280 +0,0 @@ -//! End-to-end tests of the image atomics DXIL has no operation for -//! (`image_atomic_inc`, `_dec`, `_fcmpswap`, `_fmin`, `_fmax`): synthetic -//! GFX10 compute shaders lowered to DXIL, validated by `dxil.dll` when -//! present, and run on the host GPU and WARP against RDNA2's definitions. - -use super::host::{Dispatch, Host, Root, View}; -use super::{HostShader, lower, validator}; -use crate::native::{ - ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, -}; -use crate::{io, ir, resource, structure}; - -const S_ENDPGM: u32 = 0xBF81_0000; - -/// SOP1 `s_mov_b32 sdst, src0`. -const fn s_mov_b32(sdst: u8, src0: u8) -> u32 { - 0xBE80_0000 | (sdst as u32) << 16 | 0x03 << 8 | src0 as u32 -} - -/// SMEM `s_load_dwordx{4,8} s[dst:..], s[base:base+1], byte_off` (soffset = null). -const fn s_load(op: u8, dst: u8, base: u8, byte_off: u32) -> [u32; 2] { - [ - 0x3D << 26 | (op as u32) << 18 | (dst as u32) << 6 | (base as u32 >> 1), - 125 << 25 | byte_off, - ] -} - -/// VOP1 `v_mov_b32 vdst, src0` (`src0`: 0..105 = SGPR, 128 = 0, 256.. = VGPR). -const fn v_mov_b32(vdst: u8, src0: u16) -> u32 { - 0x7E00_0000 | (vdst as u32) << 17 | 0x001 << 9 | (src0 as u32 & 0x1FF) -} - -/// MIMG `op vdata, vaddr[2], s[srsrc:srsrc+7] dmask dim:2D [glc]`. -const fn mimg(op: u8, vdata: u8, vaddr: u8, srsrc: u8, dmask: u8, glc: bool) -> [u32; 2] { - [ - 0x3C << 26 | ((op as u32) & 0x7F) << 18 | (glc as u32) << 13 | (dmask as u32) << 8 | 1 << 3, - (srsrc as u32 >> 2) << 16 | (vdata as u32) << 8 | vaddr as u32, - ] -} - -/// MUBUF `buffer_store_dword vdata, off, s[srsrc:srsrc+3], 0`. -const fn buffer_store_dword(vdata: u8, srsrc: u8) -> [u32; 2] { - [ - 0x38 << 26 | 0x1C << 18, - 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8, - ] -} - -const IMAGE_ATOMIC_SWAP: u8 = 0x0F; - -/// A one-thread compute shader: root constants `s0..s3` are (start, data, -/// compare, 0). It swaps `start` into texel (0, 0) of the R32_UINT texture -/// at heap index 1, runs `op` there with glc and the data (and compare, for -/// the two-dword forms), and stores the returned old value to dword 0 of -/// the raw UAV at heap index 0. -fn build(op: u8, pair: bool) -> HostShader { - let mut words = vec![s_mov_b32(5, 0x80)]; // s[4:5]: the table at 0 - words.extend(s_load(0x02, 8, 4, 0)); // the raw UAV - words.extend(s_load(0x03, 16, 4, 32)); // the texture - for i in 0..4u8 { - words.push(v_mov_b32(i + 1, u16::from(i))); // v1..v4 = s0..s3 - } - words.push(v_mov_b32(5, 128)); // x = 0 - words.push(v_mov_b32(6, 128)); // y = 0 - words.push(v_mov_b32(7, 256 + 1)); // the start value - words.extend(mimg(IMAGE_ATOMIC_SWAP, 7, 5, 16, 1, false)); - words.push(v_mov_b32(8, 256 + 2)); // data - words.push(v_mov_b32(9, 256 + 3)); // compare - words.extend(mimg(op, 8, 5, 16, if pair { 3 } else { 1 }, true)); - words.extend(buffer_store_dword(8, 8)); - words.push(S_ENDPGM); - - let used = |kind, table_offset_dwords, dwords| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords, - lower_bound: table_offset_dwords / 8, - stride: 0, - dwords, - user_data: 4, - slot: 1, - }; - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 12, - layout: vec![ - RootParam { - root: RootType::Constants, - table_offset_dwords: 0, - sgprs: 4, - base_register: 0, - user_data: 0, - slot: 0, - }, - RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 4, - slot: 1, - }, - ], - used: vec![used(ResourceType::Uav, 0, 4), used(ResourceType::Uav, 8, 8)], - io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 - threads: [1, 1, 1], - }), - code: words.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("resource::track"); - let io = io::raise(&p, &native).expect("io::raise"); - let lowered = 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, - crumbs: None, - emulate_mesh: false, - }) - .expect("lower"); - let shader = HostShader { - stage: HwStage::Cs, - dxil: lowered.dxil, - user_data: lowered.user_data, - static_samplers: super::build_static_samplers(&lowered.samplers, &lowered.cmp_samplers), - samplers: lowered.samplers, - root_cbvs: lowered.root_cbvs, - root_srvs: lowered.root_srvs, - address_map: lowered.address_map, - descriptor_words: lowered.descriptor_words, - root_uavs: lowered.root_uavs, - root_indexed_views: Vec::new(), - mesh_emu: None, - }; - if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { - v.validate(&mut shader.dxil.clone()) - .expect("DXIL validation failed"); - } - shader -} - -/// Runs `op` for each (start, data, compare) and checks the old value it -/// returns and the texel it leaves against `want(start, data, compare)`. -fn check(name: &str, op: u8, pair: bool, cases: &[[u32; 3]], want: impl Fn(u32, u32, u32) -> u32) { - let shader = build(op, pair); - let _one = super::valu_tests::ONE_AT_A_TIME - .lock() - .unwrap_or_else(|e| e.into_inner()); - let mut ran = 0; - for (label, warp) in [("hardware", false), ("warp", true)] { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; - }; - let (root, pso) = host - .compute_pipeline(&shader) - .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); - for &[start, data, compare] in cases { - let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; - for u in &shader.user_data { - ud[u.index as usize] = match (u.root, u.slot) { - (RootType::Constants, 0) => [start, data, compare, 0][u.dword as usize], - (RootType::Table, 1) => 0, - other => panic!("unexpected user data {other:?}"), - }; - } - let out = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![(0, Root::Constants(ud))], - views: &[View::RawUav(1), View::UintTextureUav(1, 1)], - samplers: &[], - groups: [1, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - let (old, texel) = (out[0][0], out[1][0]); - let expect = want(start, data, compare); - assert_eq!( - (old, texel), - (start, expect), - "{label}: {name}({start:#010x}, data {data:#010x}, compare {compare:#010x}) \ - returned {old:#010x} and left {texel:#010x}, want {start:#010x} and {expect:#010x}", - ); - } - ran += 1; - } - assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); -} - -#[test] -fn image_atomic_inc_wraps_at_the_data() { - let cases = [ - [0, 5, 0], - [4, 5, 0], - [5, 5, 0], - [9, 5, 0], - [7, 0, 0], - [u32::MAX - 1, u32::MAX, 0], - ]; - check("image_atomic_inc", 0x1B, false, &cases, |old, data, _| { - if old >= data { 0 } else { old + 1 } - }); -} - -#[test] -fn image_atomic_dec_reloads_at_zero_or_above_the_data() { - let cases = [ - [5, 9, 0], - [1, 9, 0], - [0, 9, 0], - [12, 9, 0], - [9, 9, 0], - [0, 0, 0], - ]; - check("image_atomic_dec", 0x1C, false, &cases, |old, data, _| { - if old == 0 || old > data { - data - } else { - old - 1 - } - }); -} - -#[test] -fn image_atomic_fcmpswap_compares_as_floats() { - let f = f32::to_bits; - let nan = 0x7FC0_0000; - let cases = [ - [f(1.5), f(7.0), f(1.5)], // equal: swapped - [f(1.5), f(7.0), f(2.5)], // unequal: kept - [0x8000_0000, f(3.0), 0], // -0 equals +0 - [nan, f(3.0), nan], // NaN equals nothing - ]; - check( - "image_atomic_fcmpswap", - 0x1D, - true, - &cases, - |old, data, compare| { - if f32::from_bits(old) == f32::from_bits(compare) { - data - } else { - old - } - }, - ); -} - -#[test] -fn image_atomic_fmin_and_fmax_keep_the_smaller_and_larger() { - let f = f32::to_bits; - let cases = [ - [f(2.0), f(-3.5), 0], - [f(-3.5), f(2.0), 0], - [f(1.0), f(1.0), 0], - [f(-0.5), f(-0.25), 0], - ]; - let pick = |min: bool| { - move |old: u32, data: u32, _| { - let (o, d) = (f32::from_bits(old), f32::from_bits(data)); - f32::to_bits(if min { d.min(o) } else { d.max(o) }) - } - }; - check("image_atomic_fmin", 0x1E, false, &cases, pick(true)); - check("image_atomic_fmax", 0x1F, false, &cases, pick(false)); -} diff --git a/crates/victory-shader/src/emit/intersect_tests.rs b/crates/victory-shader/src/emit/intersect_tests.rs index 333bc0c..0266579 100644 --- a/crates/victory-shader/src/emit/intersect_tests.rs +++ b/crates/victory-shader/src/emit/intersect_tests.rs @@ -177,8 +177,6 @@ fn build( outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - crumbs: None, - emulate_mesh: false, })?; let shader = HostShader { stage: HwStage::Cs, @@ -190,9 +188,6 @@ fn build( root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views.clone(), - mesh_emu: None, - address_map: lowered.address_map, - descriptor_words: lowered.descriptor_words, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -685,8 +680,6 @@ fn a_structure_that_returns_triangle_ids_is_refused_by_name() { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - crumbs: None, - emulate_mesh: false, }); match r { Err(ShaderError::Unsupported { what, .. }) => { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index da097a9..6196527 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -9,7 +9,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use super::UserData; -use super::bitcode::{Attr, Bin, Cast, Rmw, Term, V, pred}; +use super::bitcode::{Attr, Bin, Cast, Rmw, Tag, Term, V, pred}; use super::container::SigElement; use super::shader::{Shader, flags}; use crate::ShaderError; @@ -18,7 +18,7 @@ use crate::io::{Barycentric, Export, Input, Interp, Io, Target}; use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource}; use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source}; -use crate::structure::{Atom, Bool, BoolSet, LaneExit, Structured}; +use crate::structure::{Atom, Bool, LaneExit, Structured}; /// The ray-tracing node test (`image_bvh_intersect_ray`), a child module so /// it shares the emitter's state. @@ -41,10 +41,6 @@ enum Eval { }, } -type HandleKey = (usize, Site, u8, bool, u32, u32); - -mod global; - #[derive(Debug, Clone, Copy)] enum Val { I32(V), @@ -54,27 +50,18 @@ enum Val { pub(crate) struct Lowered { pub dxil: Vec, - /// Whether immediate sampler `n` is used for comparisons. - pub cmp_samplers: Vec, + /// Bit n: immediate sampler n is used for comparisons. + pub cmp_samplers: u64, pub root_cbvs: Vec, pub root_srvs: Vec, pub root_uavs: Vec, - - /// Reads title memory through the address map. - pub address_map: bool, - /// Reads descriptor words. - pub descriptor_words: bool, pub user_data: Vec, pub samplers: Vec<[u32; 4]>, /// The wave size the shader requires of the host, if any. pub wave_size: Option, - pub mesh_emu: Option, /// Heap handles made with a non-uniform index. #[cfg(test)] pub nonuniform_handles: u32, - /// Heap handles annotated as constant buffers. - #[cfg(test)] - pub cbuffer_handles: u32, /// Whether the program uses wave operations. #[cfg(test)] pub wave_ops: bool, @@ -91,10 +78,6 @@ pub(crate) struct Parts<'a> { pub prims: Vec, /// Mesh: what the group id arrives multiplied by. pub mesh_stride: u32, - /// With breadcrumbs (see [`super::breadcrumbs`]): the shader's slot. - #[allow(dead_code)] - pub crumbs: Option, - pub emulate_mesh: bool, } enum Stop { @@ -103,12 +86,6 @@ enum Stop { Fail(ShaderError), } -impl From for Stop { - fn from(e: ShaderError) -> Self { - Stop::Fail(e) - } -} - pub(crate) fn lower(parts: &Parts) -> Result { let mut bad = HashMap::new(); loop { @@ -127,38 +104,6 @@ pub(crate) fn lower(parts: &Parts) -> Result { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ReadDep { - Value(Value), - Edge { - from: usize, - to: usize, - value: Value, - }, -} - -struct ValueDeps { - block: usize, - guard: Option, - invert_guard: bool, - ignore_why: Option, - deps: Vec, -} - -struct OldDep { - value: Option, - direct_why: Option, - invert_guard: bool, - ignore_why: Option, -} - -struct SinkRead { - block: usize, - guard: Option, - offset: usize, - deps: Vec, -} - const TWO_PI: f32 = std::f32::consts::TAU; /// `s_sendmsg` id of a mesh or NGG stage's output allocation request. const GS_ALLOC_REQ: u16 = 9; @@ -235,7 +180,6 @@ fn half_shift(width: u32) -> u32 { struct Lower<'a> { s: Shader, x: &'a Parts<'a>, - #[allow(dead_code)] bad: &'a HashMap, lane_fail: HashMap, vals: HashMap, @@ -244,7 +188,6 @@ struct Lower<'a> { block: Vec>, cur: usize, bools: HashMap<(usize, Bool), V>, - bool_deps: HashMap<(usize, Bool), Vec>, lane_bits: HashMap, /// IR phi location by value. phi_at: HashMap, @@ -254,29 +197,19 @@ struct Lower<'a> { mask_phis: HashMap, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, - /// Phis read as data that may need a mask/missing incoming value on retry. read_phis: HashSet, - taint_candidates: HashSet, - cur_reads: Vec, - cur_old_deps: Vec, - cur_edge: Option<(usize, usize)>, - deps: HashMap>, - deps_order: Vec, - direct_missing: Vec<(Value, Why, usize, Option, bool)>, - sinks: Vec, params: HashMap, user_data: Option, user_reads: BTreeMap, - samplers: Vec<([u32; 4], bool)>, + samplers: Vec<[u32; 4]>, descriptors: HashMap<(Site, bool), &'a Source>, scalar: HashMap, exports: HashMap, interps: HashMap, - handles: HashMap, + handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>, /// Element strides read from the host's table by heap slot /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load. strides: HashMap<(usize, Site, u8), V>, - handle_deps: HashMap>, /// 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. @@ -305,7 +238,6 @@ struct Lower<'a> { split_lds: bool, /// With `split_lds`, LDS accesses in lane branches: per IR block whether every lane runs /// it, and whether the host waves meet at its start and before its exit ([`lds_meetings`]). - #[allow(clippy::type_complexity)] lds_meet: Option<(Vec, Vec<(bool, bool)>)>, /// A console wave64 program run as two host waves of 32 that exchange through LDS: the first /// of two exchange dwords, whether the group has no upper half (32 threads or fewer), and per @@ -343,7 +275,6 @@ struct Lower<'a> { mask_ok: bool, /// Ballots of masks read as data, by low dword: (low, high). ballots: HashMap, - ballot_deps: HashMap>, /// Masks whose ballot is being built: a mask whose lane bit needs its /// own value as a number (an opaque mask keyed by a dword it shares /// with another) would otherwise recurse until the stack overflows. @@ -364,16 +295,6 @@ struct Lower<'a> { counters: HashMap)>, /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. abort: Option, - /// The one block that returns: every end of the program branches to it, - /// so the function has a single exit as DXC emits it (dxil-spirv, under - /// Proton, cannot structure a loop left by both a break and a return). - ret: Option, - /// Breadcrumbs: the loops that store their count, by header, in the - /// order met (the word each owns in the shader's slot). - #[allow(dead_code)] - crumb_loops: HashMap, - /// Mesh shader lowered to compute + buffer output when emulating. - mesh_emu: Option, } /// Iterations after which a loop is left (per entry into it), unless @@ -383,9 +304,7 @@ struct Lower<'a> { /// until the driver resets it. A lane that reaches the limit leaves the /// program as killed (a pixel discards). // shortcut: a genuine loop of more iterations than this is cut short too. -// 2^20 was not low enough: a runaway data-dependent loop can outlast the -// driver's reset and freeze the desktop. 2^14 bounds it to milliseconds per wave. -pub(super) const LOOP_LIMIT: u32 = 1 << 14; +pub(super) const LOOP_LIMIT: u32 = 1 << 20; /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar /// compares, bit tests) are ballots of the lanes' booleans, taken where the @@ -439,9 +358,7 @@ fn lane_regions(st: &Structured) -> Option)>> { for (b, e) in st.exits.iter().enumerate() { match *e { LaneExit::Jump(t) => succ[b].push(t), - LaneExit::Branch { - taken, not_taken, .. - } => { + LaneExit::Branch { taken, not_taken, .. } => { succ[b].push(taken); succ[b].push(not_taken); } @@ -452,17 +369,7 @@ fn lane_regions(st: &Structured) -> Option)>> { // post-dominators (bitsets; a virtual exit after every End) let words = n.div_ceil(64); let full = vec![u64::MAX; words]; - let mut pdom: Vec> = (0..n) - .map(|b| { - if succ[b].is_empty() { - let mut v = vec![0; words]; - v[b / 64] |= 1 << (b % 64); - v - } else { - full.clone() - } - }) - .collect(); + let mut pdom: Vec> = (0..n).map(|b| if succ[b].is_empty() { let mut v = vec![0; words]; v[b / 64] |= 1 << (b % 64); v } else { full.clone() }).collect(); let mut changed = true; while changed { changed = false; @@ -485,16 +392,8 @@ fn lane_regions(st: &Structured) -> Option)>> { } let mut regions = Vec::new(); for (d, e) in st.exits.iter().enumerate() { - let LaneExit::Branch { when, .. } = *e else { - continue; - }; - if st.wide.contains(&d) - || st - .bools - .support(when) - .iter() - .all(|a| matches!(a, Atom::Uniform(_))) - { + let LaneExit::Branch { when, .. } = *e else { continue }; + if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) { continue; // a wave-wide or uniform branch: all lanes go the same way } // blocks reachable from the lane branch that do not post-dominate it @@ -519,10 +418,7 @@ fn lane_regions(st: &Structured) -> Option)>> { pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option> { let mut out = Vec::new(); for (d, region) in lane_regions(st)? { - if needs - .iter() - .any(|&b| region.get(b).copied().unwrap_or(false)) - { + if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) { st.wave_any.get(d).copied().flatten()?; out.push(d); } @@ -561,10 +457,7 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { let mut same: HashSet = HashSet::new(); for b in crate::ir::reverse_postorder(&p.blocks) { let block = &p.blocks[b]; - let whole = block - .preds - .iter() - .all(|&q| all.get(q).copied().unwrap_or(false)); + let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false)); for phi in &block.phis { if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) { same.insert(phi.value); @@ -590,18 +483,14 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { let alike = ops.iter().all(|op| match *op { Operand::Vector { reg, .. } => { // every dword of the operand the instruction reads from that register on - let read: Vec = inst - .reads - .iter() - .filter(|r| matches!(r.0, Reg::V(x) if x >= reg)) - .map(|r| r.1) - .collect(); + let read: Vec = + inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect(); !read.is_empty() && read.iter().all(|x| same.contains(x)) } // a scalar is one value; a lane mask is not, unless a compare of such values made it - Operand::Scalar { code, .. } if code != NULL => inst - .read(Reg::S(code)) - .is_none_or(|x| !is_mask(x) || same.contains(&x)), + Operand::Scalar { code, .. } if code != NULL => { + inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x)) + } _ => true, }); if alike { @@ -676,10 +565,7 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s }; // One instruction outside a section: the kind of what it writes, and whether it is a // first lane's reservation. - let step = |inst: &Inst, - kind: &HashMap, - firsts: &mut HashSet| - -> Result<(Wave, bool), Why> { + let step = |inst: &Inst, kind: &HashMap, firsts: &mut HashSet| -> Result<(Wave, bool), Why> { let name = inst.name(); let val = |op: &Operand| match *op { Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), @@ -695,9 +581,7 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s } o } - Fields::Buffer { data, .. } - if name.contains("_atomic_") || name.contains("_store_") => - { + Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => { data.iter().copied().collect() } _ => Vec::new(), @@ -717,20 +601,14 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s return Err(why(k)); } } - let w = kinds - .iter() - .copied() - .find(|&k| wild(k)) - .unwrap_or(Wave::Mixed); + let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed); let sum = |k: Wave| k == Wave::Total(Op::AddU); let is_mask = |o: &Operand| { val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v)) }; let mut reserved = false; let out = match (name, &kinds[..]) { - ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => { - Wave::First - } + ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First, ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => { Wave::Total(Op::AddU) } @@ -745,11 +623,7 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s // nothing wave-dependent goes in; what derives from a reserved base stays marked _ if !kinds.iter().any(|&k| wild(k)) => { let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. }); - if derives && kinds.contains(&Wave::Base) { - Wave::Base - } else { - Wave::Plain - } + if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain } } ("v_mov_b32" | "s_mov_b32", [k]) => *k, ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => { @@ -775,9 +649,7 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s } ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) { (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base, - (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => { - Wave::Prefix - } + (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix, (x, y) if sum(x) && sum(y) => x, _ => return Err(why(w)), }, @@ -797,11 +669,7 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s *x } ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => { - if *c == Wave::Base { - Wave::Base - } else { - Wave::Prefix - } + if *c == Wave::Base { Wave::Base } else { Wave::Prefix } } // the reservation: the first lane adds its wave's total to a shared counter (_, [Wave::Total(op)]) if name.contains("_atomic_") => { @@ -826,14 +694,9 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s }; Ok((out, reserved)) }; - let sections: Vec<_> = (0..p.blocks.len()) - .map(|b| super::wave::sections(p, b)) - .collect(); + let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect(); let order = crate::ir::reverse_postorder(&p.blocks); - let pass = |kind: &mut HashMap, - firsts: &mut HashSet, - check: bool| - -> Result<(), (usize, Why)> { + let pass = |kind: &mut HashMap, firsts: &mut HashSet, check: bool| -> Result<(), (usize, Why)> { for &b in &order { let block = &p.blocks[b]; for phi in &block.phis { @@ -862,20 +725,14 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) { Wave::Plain | Wave::Base => Wave::Total(op), // the first lane's own sum of a total is that total - Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => { - Wave::Total(op) - } + Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op), + _ => Wave::Mixed, + }, + Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Prefix, + Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix, _ => Wave::Mixed, }, - Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => { - match of(kind, Some(src)) { - Wave::Plain | Wave::Base => Wave::Prefix, - Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => { - Wave::Prefix - } - _ => Wave::Mixed, - } - } Some(_) => Wave::Mixed, }; put(kind, w, k); @@ -893,8 +750,7 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s }; // the same test as `Lower::inst`'s `effect` let effect = matches!(inst.fields, Fields::Exp { .. }) - || matches!(inst.fields, Fields::Flat { .. }) - && !name.starts_with("global_load_") + || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") || name.contains("store") || name.contains("atomic") || matches!(inst.fields, Fields::Ds { .. }) @@ -909,11 +765,7 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s let mut kw = match r { // "some lane is counted" keeps the count's kind; any other SCC is one bit of data Reg::Scc if !name.starts_with("s_bcnt1") => { - if wild(k) { - Wave::Mixed - } else { - Wave::Plain - } + if wild(k) { Wave::Mixed } else { Wave::Plain } } _ => k, }; @@ -921,10 +773,7 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s if guarded && matches!(r, Reg::V(_)) && kw == Wave::Plain - && matches!( - of(kind, inst.read(r)), - Wave::First | Wave::Total(_) | Wave::Prefix - ) + && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix) { kw = Wave::Mixed; } @@ -987,18 +836,12 @@ fn meeting_mode() -> u32 { /// barrier as before. What that cannot order is a write and a read inside one region (blocks /// joined without an all-lane block between them): refused. /// shortcut: two writes in one region are taken not to hit the same dword from both halves. -fn lds_meetings( - p: &crate::ir::Program, - st: &Structured, - all: &[bool], -) -> Option> { +fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option> { let n = st.exits.len(); let succ = |b: usize| -> Vec { match st.exits[b] { LaneExit::Jump(t) => vec![t], - LaneExit::Branch { - taken, not_taken, .. - } => vec![taken, not_taken], + LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken], LaneExit::End | LaneExit::Indirect => Vec::new(), } }; @@ -1029,10 +872,7 @@ fn lds_meetings( let r = find(&mut region, b); for i in &block.insts { let name = i.name(); - if !matches!(i.fields, Fields::Ds { .. }) - || name.starts_with("ds_swizzle") - || name.contains("permute") - { + if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") { continue; } if name.starts_with("ds_read") { @@ -1067,14 +907,7 @@ fn lane_constant_masks(st: &Structured) -> bool { LaneExit::Branch { when, .. } => Some(when), _ => None, }); - let mut work: Vec = st - .guards - .iter() - .flatten() - .flatten() - .copied() - .chain(whens) - .collect(); + let mut work: Vec = st.guards.iter().flatten().flatten().copied().chain(whens).collect(); // Through lane-mask joins too: an edge that brings a number or a constant lane set needs // the lane's own bit of it. // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such @@ -1230,8 +1063,8 @@ pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { /// second row. An element that shares a register behind another one (the /// signature packs a short element into the free columns of an earlier /// register) is NOT in that row's halves: it follows in the first -/// parameter, in row order, that has whole dwords left. Grand Theft Auto -/// VI's packed pedestrian shaders show both cases: TEXCOORD7 (register 1, +/// parameter, in row order, that has whole dwords left. +/// The title's packed pedestrian shaders show both cases: TEXCOORD7 (register 1, /// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3 /// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4, /// column 3, behind the three columns of TEXCOORD4) in dword 3 of @@ -1239,7 +1072,6 @@ pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { /// TEXCOORD4's second dword stays zero. type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>; -#[allow(clippy::type_complexity)] fn packed_layout(elements: &[SigElement], packs: &[(u8, Option)]) -> PackedLayout { let of_row = |r: u8| { let mut of: Vec<&SigElement> = elements @@ -1253,7 +1085,6 @@ fn packed_layout(elements: &[SigElement], packs: &[(u8, Option)]) -> PackedL packs.sort_unstable(); packs.dedup_by_key(|p| p.0); // Per parameter: its first row, the dwords used, the elements. - #[allow(clippy::type_complexity)] let mut layout: Vec<(u8, u8, Vec<(u8, u8, u8, u8)>)> = Vec::new(); let mut behind = Vec::new(); for &(a, b) in &packs { @@ -1390,39 +1221,6 @@ fn half_input_partners(io: &StageIo, inputs: &[SigElement]) -> HashMap { partners } -/// The image atomics made by [`Lower::atomic_loop`], in place of a DXIL -/// atomic operation code. -const ATOMIC_LOOP: u32 = u32::MAX - 1; - -/// Why dword `rel` of a GFX10 image (`image`) or buffer descriptor has no -/// value when the program reads it as a number: what the dword holds. -/// `None` past the descriptor. -fn descriptor_field(image: bool, rel: u32) -> Option { - Some(match (image, rel) { - (true, 0) => "an image descriptor's address read as data", - (true, 5) => "an image descriptor's array pitch or mip limits read as data", - (true, 6) => "an image descriptor's compression fields read as data", - (true, 7) => "an image descriptor's metadata address read as data", - (false, 0) => "a buffer descriptor's address read as data", - (false, 1) => "a buffer descriptor's stride or high address read as data", - (false, 3) => "a buffer descriptor's format or swizzle read as data", - _ => return None, - }) -} - -/// Why a scalar memory instruction other than a load of dwords has no -/// value here, named by what it is. -fn smem_reason(name: &str) -> Why { - match name { - "s_memtime" | "s_memrealtime" => "a timestamp read as data", - "s_get_waveid_in_workgroup" => "a wave's index in its group read as data", - "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => "a scalar cache instruction", - n if n.contains("_store_") => "a scalar memory store", - n if n.starts_with("s_scratch_load") => "a scalar scratch load", - _ => "a scalar memory read as data", - } -} - fn unsupported(offset: usize, what: Why) -> Stop { Stop::Fail(ShaderError::Unsupported { offset, what }) } @@ -1441,17 +1239,14 @@ impl<'a> Lower<'a> { s.outputs = x.outputs.clone(); let insts = || p.blocks.iter().flat_map(|b| &b.insts); let writes_uavs = insts().any(|i| { - matches!( - i.fields, - Fields::Image { .. } | Fields::Buffer { .. } | Fields::Flat { .. } - ) && (i.name().contains("store") || i.name().contains("atomic")) + matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. }) + && (i.name().contains("store") || i.name().contains("atomic")) }); let mut console_lanes = false; // LDS accesses get a group barrier each (a console wave split in two host waves) let mut split_lds = false; // with `split_lds`, LDS accesses in lane branches: the blocks every lane runs, and // where the host waves meet around those branches (`lds_meetings`) - #[allow(clippy::type_complexity)] let mut lds_meet: Option<(Vec, Vec<(bool, bool)>)> = None; // a console wave64 program in two host waves of 32 (`exchange`) let mut exchange: Option<(u32, bool, Vec)> = None; @@ -1468,55 +1263,10 @@ impl<'a> Lower<'a> { n.starts_with("ds_swizzle") || n.contains("permute") || n.starts_with("v_mbcnt") - || matches!( - n, - "v_readlane_b32" - | "v_writelane_b32" - | "v_permlane16_b32" - | "v_permlanex16_b32" - ) + || matches!(n, "v_readlane_b32" | "v_writelane_b32") || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some()) || reads_mask_as_data(x.st, i) - }) || { - // Masks held as numbers or constant lane sets: the lane - // tests its own bit by its console lane. - let whens = x.st.exits.iter().filter_map(|e| match *e { - LaneExit::Branch { when, .. } => Some(when), - _ => None, - }); - let mut all: Vec = - x.st.guards - .iter() - .flatten() - .flatten() - .copied() - .chain(whens) - .collect(); - all.sort_unstable(); - all.dedup(); - all.into_iter().any(|g| { - x.st.bools - .support(g) - .iter() - .any(|a| matches!(a, Atom::Opaque(_) | Atom::Constant(_))) - }) || insts().any(|i| { - matches!( - i.name(), - "v_cndmask_b32" - | "v_add_co_ci_u32" - | "v_sub_co_ci_u32" - | "v_subrev_co_ci_u32" - ) && match &i.fields { - Fields::Valu(v) => match v.src.get(2) { - Some(&Operand::Scalar { code, .. }) => i - .read(Reg::S(code)) - .is_none_or(|m| !x.st.masks.contains_key(&m)), - _ => false, - }, - _ => false, - } - }) - } || lane_constant_masks(x.st) + }) || lane_constant_masks(x.st) // (a branch the wave takes together asks the wave) || !x.st.wide.is_empty(); let mut wave = if x.native.wave64 { 64 } else { 32 }; @@ -1530,10 +1280,7 @@ impl<'a> Lower<'a> { // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant // masks), nor when LDS may be shared within the console wave without barriers (a // group over 32 threads with LDS): those still need 64-lane waves. - if wave == 64 - && host_max_wave() == 32 - && (console_lanes || one_wave && s.lds_dwords > 0) - { + if wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) { let crosses = insts().any(|i| { let n = i.name(); n.starts_with("v_mbcnt") @@ -1558,9 +1305,9 @@ impl<'a> Lower<'a> { }; if let Some(all) = all_lane_blocks(x.st) { let ok = p.blocks.iter().enumerate().all(|(b, blk)| { - blk.insts - .iter() - .all(|inst| !lds(inst) || all.get(b).copied().unwrap_or(false)) + blk.insts.iter().all(|inst| { + !lds(inst) || all.get(b).copied().unwrap_or(false) + }) }); let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok; if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) { @@ -1571,9 +1318,7 @@ impl<'a> Lower<'a> { // (the blocks whose LDS accesses not every lane runs: with the // branches around them taken wave-wide they get their barriers) for (b, blk) in p.blocks.iter().enumerate() { - if !all.get(b).copied().unwrap_or(false) - && blk.insts.iter().any(lds) - { + if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) { need(b); } } @@ -1626,11 +1371,7 @@ impl<'a> Lower<'a> { } } why.sort_unstable(); - eprintln!( - "WAVE64-WHY group={group} lds={} [{}]", - s.lds_dwords > 0, - why.join(", ") - ); + eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", ")); } } if wave == 32 && x.native.wave64 { @@ -1657,11 +1398,12 @@ impl<'a> Lower<'a> { let at = |b: usize| place.get(b).copied().unwrap_or(usize::MAX); at(from) != usize::MAX && at(to) <= at(from) }; - let cut_short = - x.st.exits - .iter() - .enumerate() - .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t))); + let cut_short = x + .st + .exits + .iter() + .enumerate() + .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t))); let all = all_lane_blocks(x.st); (0..p.blocks.len()) .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier")) @@ -1676,23 +1418,15 @@ impl<'a> Lower<'a> { HashSet::new() }; let mut no_barrier = HashSet::new(); - let mut mesh_emu = None; if let StageIo::Ms(ms) = &x.native.io { + s.prims = x.prims.clone(); s.threads = Some([ms.threads, 1, 1]); s.lds_dwords = ms.lds_bytes.div_ceil(4); - if x.emulate_mesh { - s.inputs.clear(); - s.outputs.clear(); - s.prims.clear(); - mesh_emu = Some(mesh_emu_state(ms, x)); - } else { - s.prims = x.prims.clone(); - s.mesh = Some(super::shader::Mesh { - max_vertices: ms.max_vertices, - max_primitives: ms.max_primitives, - topology: ms.topology, - }); - } + s.mesh = Some(super::shader::Mesh { + max_vertices: ms.max_vertices, + max_primitives: ms.max_primitives, + topology: ms.topology, + }); // Barriers order the lanes' LDS accesses; the console's // allocation request needs them too, but the host does not. One // lane sends that request, and what it dominates (the path for @@ -1738,25 +1472,15 @@ impl<'a> Lower<'a> { block: vec![None; p.blocks.len()], cur: 0, bools: HashMap::new(), - bool_deps: HashMap::new(), lane_bits: HashMap::new(), phi_at, mask_phis: HashMap::new(), pending_masks: Vec::new(), data_phis: Vec::new(), read_phis: HashSet::new(), - taint_candidates: HashSet::new(), - cur_reads: Vec::new(), - cur_old_deps: Vec::new(), - cur_edge: None, - deps: HashMap::new(), - deps_order: Vec::new(), - direct_missing: Vec::new(), - sinks: Vec::new(), stale: HashSet::new(), params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), user_data: None, - crumb_loops: HashMap::new(), user_reads: BTreeMap::new(), samplers: Vec::new(), descriptors: x @@ -1767,9 +1491,24 @@ impl<'a> Lower<'a> { .collect(), scalar: x.res.scalar.iter().copied().collect(), exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), - interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(), + interps: { + let mut m: HashMap = x.io.interps.iter().map(|(s, i)| (*s, i)).collect(); + // A first half whose result is also read as data (an f16 second half keeps + // the other half of its dst, PS_DeferredTextured): evaluated as the pair it + // starts. Approximate for those other bits (P0 + i P10 on the console); a + // first half only the second half reads is gone before lowering. + if std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") { + for (_, i) in &x.io.interps { + if let Interp::Interpolated { first, .. } = i { + for s in first { + m.entry(*s).or_insert(i); + } + } + } + } + m + }, handles: HashMap::new(), - handle_deps: HashMap::new(), strides: HashMap::new(), edges: HashMap::new(), exported: vec![false; p.blocks.len()], @@ -1809,7 +1548,6 @@ impl<'a> Lower<'a> { }, mask_ok: false, ballots: HashMap::new(), - ballot_deps: HashMap::new(), balloting: HashSet::new(), def_block: p .blocks @@ -1829,8 +1567,6 @@ impl<'a> Lower<'a> { code_table: None, counters: HashMap::new(), abort: None, - ret: None, - mesh_emu, } } @@ -1900,17 +1636,6 @@ impl<'a> Lower<'a> { unreachable!() }; let name = inst.name(); - if self.is_global((b, i)) { - return if name.starts_with("global_load_") { - self.global_load(inst, b, i) - } else if name.starts_with("global_store_") { - self.global_store(inst, b, i) - } else if name.starts_with("global_atomic_") { - self.global_atomic(inst, b, i) - } else { - Err("a global access to title memory") - }; - } if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) { return self.memory_flat(inst, b, i); } @@ -2044,19 +1769,11 @@ impl<'a> Lower<'a> { const UNKNOWN: Why = "a whole-wave section step the simulation does not follow"; let inst = &self.x.p.blocks[b].insts[i]; for &(_, w) in &inst.writes { - self.cur_reads.clear(); - self.cur_edge = None; let val = if self.section_out.contains(&w) { let shape = self.sections[&b][&start].shapes.get(&w).copied(); let own = self.own_bits.totals.contains(&w); match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh, own)) { - Ok(x) => { - let reads = std::mem::take(&mut self.cur_reads); - if !reads.is_empty() { - self.record_write_deps(w, b, None, false, None, reads); - } - Val::I32(x) - } + Ok(x) => Val::I32(x), Err(why) => Val::Missing(why), } } else { @@ -2080,6 +1797,9 @@ impl<'a> Lower<'a> { Shape::K(k) => return Ok(self.s.m.i32(k)), Shape::Value(v) => return self.i32_of(v), Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None), + Shape::ActiveF64(lo, hi, mask, high) => { + return self.active_f64_sum(lo, hi, mask, high); + } Shape::Masked(src, mask, ident) => { let c = self.cur; let &m = self @@ -2202,14 +1922,7 @@ impl<'a> Lower<'a> { Some(_) => { // the upper half adds the lower half's total to its prefix let (k0, ku) = (self.s.m.i8(0), self.s.m.i8(u8::from(!float))); - let total = self.s.op( - c, - &format!("waveActiveOp.{sfx}"), - Attr::NoUnwind, - ty, - 119, - &[arg, k0, ku], - ); + let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]); let tb = bits(self, total); let c = self.cur; let (lo, _) = self.exchange_halves(c, tb); @@ -2217,11 +1930,7 @@ impl<'a> Lower<'a> { let cl = self.console_lane(); let k32 = self.s.m.i32(32); let upper = self.s.m.cmp(c, pred::IUGE, cl, k32); - let zero = if float { - self.s.m.f32(0) - } else { - self.s.m.i32(0) - }; + let zero = if float { self.s.m.f32(0) } else { self.s.m.i32(0) }; let add = self.s.m.select(c, upper, lo, zero); self.s.m.bin(c, Bin::Add, r, add) } @@ -2245,14 +1954,7 @@ impl<'a> Lower<'a> { Op::MinI => 38, _ => 37, }; - self.s.op( - c, - &format!("binary.{sfx}"), - Attr::ReadNone, - ty, - code, - &[lo, hi], - ) + self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi]) } } } @@ -2263,6 +1965,74 @@ impl<'a> Lower<'a> { Ok(if float { self.as_int(r) } else { r }) } + /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere), + /// returning the low (`!high`) or high (`high`) 32-bit word. + fn active_f64_sum( + &mut self, + lo: Value, + hi: Value, + mask: Value, + high: bool, + ) -> Result { + if self.mask_data == MaskData::None { + return Err("a wave reduction in a mesh shader"); + } + let c = self.cur; + let &m = self + .x + .st + .masks + .get(&mask) + .ok_or("a wave reduction's untracked mask")?; + let on = self.boolean(m, c)?; + let lo = self.i32_of(lo)?; + let hi = self.i32_of(hi)?; + let z = self.s.m.i32(0); + let lo = self.s.m.select(c, on, lo, z); + let hi = self.s.m.select(c, on, hi, z); + self.s.flags |= flags::WAVE_OPS | flags::DOUBLES; + let f64t = self.s.m.double(); + let i32t = self.s.t.i32; + let split_ty = self + .s + .m + .named_struct("dx.types.splitdouble", vec![i32t, i32t]); + let arg = self + .s + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]); + let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0)); + let sum = self + .s + .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]); + let split = self + .s + .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]); + let mut r_lo = self.s.m.extract(c, split, 0); + let mut r_hi = self.s.m.extract(c, split, 1); + if self.exchange.is_some() { + if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); + return Err("a wave reduction where not every lane runs"); + } + let (lo0, lo1) = self.exchange_halves(self.cur, r_lo); + let (hi0, hi1) = self.exchange_halves(self.cur, r_hi); + let c = self.cur; + let d0 = self + .s + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]); + let d1 = self + .s + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]); + let total = self.s.m.bin(c, Bin::Add, d0, d1); + let split = self + .s + .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]); + r_lo = self.s.m.extract(c, split, 0); + r_hi = self.s.m.extract(c, split, 1); + } + Ok(if high { r_hi } else { r_lo }) + } + /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest /// ([`Self::f16_nearest`]). @@ -2283,7 +2053,7 @@ impl<'a> Lower<'a> { /// lanes outside the mask), bit for bit as the console adds it: every addition rounds to /// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes /// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves; - /// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the + /// `super::wave::buddies`). Each lane adds its partner's partial sum, read from the /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange /// their halves' sums for the last addition. The high half of the result is lane 0's, /// which no `v_add_f16` writes. @@ -2292,10 +2062,7 @@ impl<'a> Lower<'a> { /// own (half a sum is no sum). fn half_sum(&mut self, x: V) -> Result { const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs"; - let threads = self - .s - .threads - .ok_or("a wave sum of 16-bit floats outside compute")?; + let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?; if threads.iter().product::() % 64 != 0 { return Err("a wave sum of 16-bit floats in a wave that is not full"); } @@ -2311,8 +2078,7 @@ impl<'a> Lower<'a> { let every = if halves { self.all_lanes(self.cur_ir) } else { - all_lane_blocks(self.x.st) - .is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false)) + all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false)) }; if !every { if halves { @@ -2322,9 +2088,7 @@ impl<'a> Lower<'a> { } let c = self.cur; let i32t = self.s.t.i32; - let lane = self - .s - .op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let mut sum = x; for step in 0..if halves { 5 } else { 6 } { let bit = self.s.m.i32(1 << step); @@ -2332,11 +2096,7 @@ impl<'a> Lower<'a> { let theirs = self.read_lane(sum, partner); sum = self.add_halves(sum, theirs); } - let (high, low, zero) = ( - self.s.m.i32(0xFFFF_0000), - self.s.m.i32(0xFFFF), - self.s.m.i32(0), - ); + let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0)); let first = self.read_lane(x, zero); let first = self.s.m.bin(c, Bin::And, first, high); let sum = self.s.m.bin(c, Bin::And, sum, low); @@ -2365,20 +2125,6 @@ impl<'a> Lower<'a> { self.s.m.new_block() }); } - self.cur = self.s.entry; - self.find_sections(); - if self.mesh_emu.is_some() { - self.mesh_emu_init().map_err(|w| unsupported(0, w))?; - } - self.inputs()?; - if let Some(mesh) = self.s.mesh { - self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?; - } else if self.mesh_emu.is_some() { - self.mesh_emu_prologue(); - } - if self.cur != self.s.entry { - self.block[order[0]] = Some(self.cur); - } // Loop headers count iterations (`LOOP_LIMIT`). for &b in &order { let header = p.blocks[b] @@ -2391,6 +2137,13 @@ impl<'a> Lower<'a> { self.counters.insert(b, (phi, Vec::new())); } } + self.cur = self.s.entry; + self.find_sections(); + self.inputs()?; + if let Some(mesh) = self.s.mesh { + self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?; + self.block[order[0]] = Some(self.cur); + } for &b in &order { self.cur = self.block[b].expect("reachable"); self.cur_ir = b; @@ -2408,13 +2161,11 @@ impl<'a> Lower<'a> { Reg::Scc => { let v = self.s.m.phi(self.cur, self.s.t.i1); self.data_phis.push((v, b, i)); - self.taint_candidates.insert(phi.value); Val::Bit(v) } _ => { let v = self.s.m.phi(self.cur, self.s.t.i32); self.data_phis.push((v, b, i)); - self.taint_candidates.insert(phi.value); Val::I32(v) } }; @@ -2441,39 +2192,28 @@ impl<'a> Lower<'a> { } self.tail[b] = Some(self.cur); self.exit(b)?; - // A breadcrumb may have ended the block (a back edge's counting). - self.tail[b] = Some(self.cur); } self.fill_phis()?; let user_data = self.user_reads.values().copied().collect(); - let (samplers, cmp_samplers): (Vec<_>, Vec<_>) = self.samplers.into_iter().unzip(); - self.s.samplers = cmp_samplers.clone(); + self.s.samplers = self.samplers.len() as u32; let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect(); let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect(); - let cmp_samplers = self.s.samplers.clone(); + let cmp_samplers = self.s.cmp_samplers; let wave_size = self.s.wave_size; - let address_map = self.s.address_map.is_some(); - let descriptor_words = self.s.descriptor_words.is_some(); - let mesh_emu = self.mesh_emu.take().map(MeshEmuState::finish); Ok(Lowered { wave_size, cmp_samplers, root_cbvs, root_srvs, root_uavs, - address_map, - descriptor_words, - mesh_emu, #[cfg(test)] nonuniform_handles: self.s.nonuniform_handles, #[cfg(test)] - cbuffer_handles: self.s.cbuffer_handles, - #[cfg(test)] wave_ops: self.s.flags & flags::WAVE_OPS != 0, dxil: self.s.finish(), user_data, - samplers, + samplers: self.samplers, }) } @@ -2487,7 +2227,7 @@ impl<'a> Lower<'a> { } /// Values of the program's input registers. - fn inputs(&mut self) -> Result<(), ShaderError> { + fn inputs(&mut self) -> Result<(), Stop> { let io_inputs: HashMap = self.x.io.inputs.iter().copied().collect(); for &(reg, v) in &self.x.p.inputs { let val = match reg { @@ -2546,9 +2286,6 @@ impl<'a> Lower<'a> { Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c), Input::GroupInfo => return Val::Missing("the thread-group info SGPR"), Input::MeshGroup => { - if self.mesh_emu.is_some() { - return self.mesh_group_emu(); - } let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else { unreachable!() }; @@ -2683,48 +2420,8 @@ impl<'a> Lower<'a> { } } - fn record_read(&mut self, v: Value) { - if !self.taint_candidates.contains(&v) { - return; - } - let dep = match self.cur_edge { - Some((from, to)) => ReadDep::Edge { from, to, value: v }, - None => ReadDep::Value(v), - }; - if !self.cur_reads.contains(&dep) { - self.cur_reads.push(dep); - } - } - - fn record_write_deps( - &mut self, - w: Value, - block: usize, - guard: Option, - invert_guard: bool, - ignore_why: Option, - deps: Vec, - ) { - self.taint_candidates.insert(w); - let list = self.deps.entry(w).or_insert_with(|| { - self.deps_order.push(w); - Vec::new() - }); - list.push(ValueDeps { - block, - guard, - invert_guard, - ignore_why, - deps, - }); - } - /// The DXIL form of an IR value. fn get(&mut self, v: Value) -> Result { - self.get_inner(v, true) - } - - fn get_inner(&mut self, v: Value, track: bool) -> Result { if self.phi_at.contains_key(&v) { self.read_phis.insert(v); } @@ -2734,12 +2431,7 @@ impl<'a> Lower<'a> { return self.mask_dword(v).map(Val::I32); } Some(&Val::Missing(w)) => return Err(w), - Some(&val) => { - if track { - self.record_read(v); - } - return Ok(val); - } + Some(&val) => return Ok(val), None => {} } if let Some(&(param, dword)) = self.params.get(&v) { @@ -2754,50 +2446,6 @@ impl<'a> Lower<'a> { Err("a value defined after its use") } - /// Reads an overwritten register's previous value, recording its lane - /// dependency (`invert_guard` for `!guard`, active lanes otherwise) so - /// direct missing values and tainted phis still propagate where kept. - fn old_i32_of(&mut self, v: Option, invert_guard: bool, ignore_why: Option) -> V { - let Some(v) = v else { - return self.s.m.i32(0); - }; - match self.get_inner(v, false) { - Ok(Val::I32(x)) => { - if self.taint_candidates.contains(&v) { - self.cur_old_deps.push(OldDep { - value: Some(v), - direct_why: None, - invert_guard, - ignore_why, - }); - } - x - } - Ok(Val::Bit(x)) => { - if self.taint_candidates.contains(&v) { - self.cur_old_deps.push(OldDep { - value: Some(v), - direct_why: None, - invert_guard, - ignore_why, - }); - } - self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32) - } - Ok(Val::Missing(why)) | Err(why) => { - if ignore_why != Some(why) { - self.cur_old_deps.push(OldDep { - value: None, - direct_why: Some(why), - invert_guard, - ignore_why, - }); - } - self.s.m.i32(0) - } - } - } - /// Loads `v` if it is a barycentric input VGPR not loaded yet (see /// `inputs`): `None` if it is not one. fn lazy_barycentric(&mut self, v: Value) -> Option> { @@ -2977,24 +2625,6 @@ impl<'a> Lower<'a> { self.s.m.extract(entry, r, index % 4) } - /// The entry-block load of user-data dword `data`, whose `index` is the - /// console's absolute index: the host binds it relative to - /// [`Self::user_first`]. - #[allow(dead_code)] - fn user_dword(&mut self, data: UserData) -> V { - let rel = data.index - self.user_first(); - self.user_reads.insert(rel, UserData { index: rel, ..data }); - self.user_at(rel) - } - - fn extend_cur_reads(&mut self, extra: &[ReadDep]) { - for &dep in extra { - if !self.cur_reads.contains(&dep) { - self.cur_reads.push(dep); - } - } - } - /// Whether some instruction computes with `v` (scalar or vector /// arithmetic), rather than only naming it in a descriptor operand, /// moving it (at most `depth` moves are followed) or comparing it: a @@ -3077,10 +2707,7 @@ impl<'a> Lower<'a> { .m .cmp(c, if off > 0 { pred::IULT } else { pred::IUGT }, sum, lo); let one = self.s.m.cast(c, Cast::ZExt, wrapped, i32t); - let hi = self - .s - .m - .bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one); + let hi = self.s.m.bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one); (sum, hi) } @@ -3090,9 +2717,7 @@ impl<'a> Lower<'a> { /// (and drops writes) through the null view at the first slot, and its /// number is left for the host, for lanes that run (`guard`). fn memory(&mut self, lo: V, hi: V, guard: Option) -> (V, V) { - use super::shader::{ - MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE, - }; + use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE}; let c = self.cur; let (i32t, res) = (self.s.t.i32, self.s.t.res_ret); let k = |l: &mut Self, v: u32| l.s.m.i32(v); @@ -3107,6 +2732,7 @@ impl<'a> Lower<'a> { let page = self .s .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]); + self.s.m.tag(page, Tag::Clamp); let k3 = k(self, 3); let at = self.s.m.bin(c, Bin::Shl, page, k3); let directory = self.s.root_srv_handle(SLOT_MEMORY); @@ -3229,14 +2855,8 @@ impl<'a> Lower<'a> { args.push(self.s.m.i8((1u8 << n) - 1)); args.push(align); let at = self.begin_guarded(guard); - self.s.op( - self.cur, - "rawBufferStore.i32", - Attr::NoUnwind, - void, - 140, - &args, - ); + self.s + .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args); self.end_guarded(at, &[]); return Ok(()); } @@ -3315,9 +2935,9 @@ impl<'a> Lower<'a> { let fseen = self.as_float(seen); // `dx.op.binary`: FMax 35, FMin 36. let pick = if op == "fmin" { 36 } else { 35 }; - let wanted = - self.s - .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]); + let wanted = self + .s + .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]); let wanted = self.as_int(wanted); let found = self.s.op( pass, @@ -3370,9 +2990,7 @@ impl<'a> Lower<'a> { _ => return Err("a scalar memory access by address"), }; let word = |l: &mut Self, k: u8| -> Result { - let v = inst - .read(Reg::S(base + k)) - .ok_or("an address not in SGPRs")?; + let v = inst.read(Reg::S(base + k)).ok_or("an address not in SGPRs")?; l.i32_of(v) }; let (mut lo, mut hi) = (word(self, 0)?, word(self, 1)?); @@ -3422,8 +3040,7 @@ impl<'a> Lower<'a> { // say) is the ballot of the lanes that are there: all of them, where two exchanging // host waves know every lane runs that block. let made = self.def_block.get(&lo).copied(); - let whole = - self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b)); + let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b)); if !self.x.st.active.contains(&lo) && !whole { if self.exchange.is_some() && !self.local { need(made.unwrap_or(0)); @@ -3431,13 +3048,7 @@ impl<'a> Lower<'a> { return Err(MASK_ELSEWHERE); } let (x, y) = match self.ballots.get(&lo) { - Some(&xy) => { - if let Some(deps) = self.ballot_deps.get(&lo) { - let deps = deps.clone(); - self.extend_cur_reads(&deps); - } - xy - } + Some(&xy) => xy, None => { let at = match self.def_block.get(&lo) { // Program inputs (EXEC on entry). @@ -3448,15 +3059,9 @@ impl<'a> Lower<'a> { if !self.balloting.insert(lo) { return Err("a lane mask whose lanes depend on its own value"); } - let saved = std::mem::take(&mut self.cur_reads); let bit = self.boolean(m, at); self.balloting.remove(&lo); - let sub = std::mem::replace(&mut self.cur_reads, saved); let bit = bit?; - self.extend_cur_reads(&sub); - if !sub.is_empty() { - self.ballot_deps.insert(lo, sub); - } let i32t = self.s.t.i32; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); let r = self @@ -3471,9 +3076,7 @@ impl<'a> Lower<'a> { if !self.local_ok && !self.local_any { return Err("a lane mask read as data in a half-wave"); } - } else if !self.exchange.as_ref().is_some_and(|e| e.1) - && !b.is_none_or(|b| self.all_lanes(b)) - { + } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) { // (a group of 32 or fewer has no other half to exchange with) need(b.unwrap_or(0)); return Err("a lane mask exchanged where not every lane runs"); @@ -3581,7 +3184,13 @@ impl<'a> Lower<'a> { Reg::S(reg) }; let val = inst.read(r).ok_or("an unread operand")?; - self.float_of(val)? + match self.floats.get(&val) { + Some(&f) => f, + None => { + let x = self.i32_of(val)?; + self.as_float(x) + } + } } _ => { let x = self.operand(inst, &op)?; @@ -3792,69 +3401,6 @@ impl<'a> Lower<'a> { self.s.m.select(c, nan, least, median) } - /// `v_div_fixup_f32` / `v_div_fixup_f16`: finalizes a division sequence's - /// quotient `quot` (`src0`) for `num / denom` (`src2 / src1`), resolving - /// IEEE-754 special cases (`NaN`, `0/0`, `inf/inf`, `x/0`, `x/inf`, - /// `0/x`, `inf/x`, and `quot == NaN` overflow) and applying `sign(denom) - /// ^ sign(num)` in pure integer bit operations. - fn div_fixup(&mut self, quot: V, denom: V, num: V) -> V { - let c = self.cur; - let k = |l: &mut Self, v: u32| l.s.m.i32(v); - let q = self.as_int(quot); - let d = self.as_int(denom); - let n = self.as_int(num); - - let sign_mask = k(self, 0x8000_0000); - let abs_mask = k(self, 0x7FFF_FFFF); - let inf_bits = k(self, 0x7F80_0000); - let qnan_bits = k(self, 0x7FC0_0000); - let quiet_bit = k(self, 0x0040_0000); - let zero = k(self, 0); - - let sign_xor = self.s.m.bin(c, Bin::Xor, d, n); - let sign_out = self.s.m.bin(c, Bin::And, sign_xor, sign_mask); - - let q_mag = self.s.m.bin(c, Bin::And, q, abs_mask); - let d_mag = self.s.m.bin(c, Bin::And, d, abs_mask); - let n_mag = self.s.m.bin(c, Bin::And, n, abs_mask); - - let q_nan = self.s.m.cmp(c, pred::IUGT, q_mag, inf_bits); - let d_nan = self.s.m.cmp(c, pred::IUGT, d_mag, inf_bits); - let n_nan = self.s.m.cmp(c, pred::IUGT, n_mag, inf_bits); - - let d_inf = self.s.m.cmp(c, pred::EQ, d_mag, inf_bits); - let n_inf = self.s.m.cmp(c, pred::EQ, n_mag, inf_bits); - let d_zero = self.s.m.cmp(c, pred::EQ, d_mag, zero); - let n_zero = self.s.m.cmp(c, pred::EQ, n_mag, zero); - - let signed_inf = self.s.m.bin(c, Bin::Or, inf_bits, sign_out); - let signed_zero = sign_out; - let signed_q = self.s.m.bin(c, Bin::Or, q_mag, sign_out); - - // Priority (lowest to highest, built bottom-up via select): - // 6. Normal/inf quotient: copysign(quot, sign_out); NaN quotient -> ±inf. - let r = self.s.m.select(c, q_nan, signed_inf, signed_q); - // 5. denom == ±inf or num == ±0 -> ±0.0 with sign_out. - let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero); - let r = self.s.m.select(c, make_zero, signed_zero, r); - // 4. num == ±inf or denom == ±0 -> ±inf with sign_out. - let make_inf = self.s.m.bin(c, Bin::Or, n_inf, d_zero); - let r = self.s.m.select(c, make_inf, signed_inf, r); - // 3. (0 / 0) or (inf / inf) -> canonical qNaN. - let zero_over_zero = self.s.m.bin(c, Bin::And, d_zero, n_zero); - let inf_over_inf = self.s.m.bin(c, Bin::And, d_inf, n_inf); - let indet = self.s.m.bin(c, Bin::Or, zero_over_zero, inf_over_inf); - let r = self.s.m.select(c, indet, qnan_bits, r); - // 2. num is NaN -> quiet(num). - let n_quiet = self.s.m.bin(c, Bin::Or, n, quiet_bit); - let r = self.s.m.select(c, n_nan, n_quiet, r); - // 1. denom is NaN -> quiet(denom). - let d_quiet = self.s.m.bin(c, Bin::Or, d, quiet_bit); - let r = self.s.m.select(c, d_nan, d_quiet, r); - - self.as_float(r) - } - /// `a - floor(a)`, which on the hardware never reaches 1.0: where it /// would round to it (a tiny negative `a`), the result is `below_one`, /// the largest value under 1.0 in the operation's width. Hosts differ @@ -3921,65 +3467,6 @@ impl<'a> Lower<'a> { self.s.m.select(c, z, zero, m) } - /// Decomposes an f32 into `(mantissa, exponent)` per RDNA2 `v_frexp_*`: - /// - finite non-zero (normal or subnormal): `mantissa` in `(-1, -0.5] U [0.5, 1)` - /// and `exponent` such that `a == mantissa * 2^exponent`; - /// - `±0`, `±inf`, `NaN`: `mantissa = a` (preserving sign/special value), `exponent = 0`. - fn frexp_f32(&mut self, a: V) -> (V, V) { - let c = self.cur; - let k = |l: &mut Self, x: u32| l.s.m.i32(x); - let bits = self.as_int(a); - let sign_mask = k(self, 0x8000_0000); - let mag_mask = k(self, 0x7FFF_FFFF); - let mant_mask = k(self, 0x007F_FFFF); - let half_exp = k(self, 0x3F00_0000); - let (k0, k23, k255, k126) = (k(self, 0), k(self, 23), k(self, 255), k(self, 126)); - - let sign = self.s.m.bin(c, Bin::And, bits, sign_mask); - let mag = self.s.m.bin(c, Bin::And, bits, mag_mask); - let exp_raw = self.s.m.bin(c, Bin::LShr, mag, k23); - let mant_raw = self.s.m.bin(c, Bin::And, mag, mant_mask); - - // Normal path: biased exponent 1..=254 -> exponent = exp_raw - 126, mantissa exp = 126. - let norm_mant = self.s.m.bin(c, Bin::Or, sign, half_exp); - let norm_mant = self.s.m.bin(c, Bin::Or, norm_mant, mant_raw); - let norm_exp = self.s.m.bin(c, Bin::Sub, exp_raw, k126); - - // Subnormal path (exp_raw == 0, mant_raw != 0): shift top bit of mant_raw to bit 23. - // FirstbitHi (op 33) counts leading zeros from bit 31: bit k -> lz = 31 - k in [9..=31]. - let lz = self.s.op( - c, - "unaryBits.i32", - Attr::ReadNone, - self.s.t.i32, - 33, - &[mant_raw], - ); - let k8 = k(self, 8); - let sh = self.s.m.bin(c, Bin::Sub, lz, k8); - let k31 = k(self, 31); - let sh_safe = self.s.m.bin(c, Bin::And, sh, k31); - let sub_mant_bits = self.s.m.bin(c, Bin::Shl, mant_raw, sh_safe); - let sub_mant_bits = self.s.m.bin(c, Bin::And, sub_mant_bits, mant_mask); - let sub_mant = self.s.m.bin(c, Bin::Or, sign, half_exp); - let sub_mant = self.s.m.bin(c, Bin::Or, sub_mant, sub_mant_bits); - // Value = mant_raw * 2^-149 = (0.5..1) * 2^(-117 - lz). - let k_neg117 = k(self, (-117i32) as u32); - let sub_exp = self.s.m.bin(c, Bin::Sub, k_neg117, lz); - - let is_exp0 = self.s.m.cmp(c, pred::EQ, exp_raw, k0); - let is_zero = self.s.m.cmp(c, pred::EQ, mag, k0); - let is_inf_nan = self.s.m.cmp(c, pred::EQ, exp_raw, k255); - let is_special = self.s.m.bin(c, Bin::Or, is_zero, is_inf_nan); - - let mant_fin = self.s.m.select(c, is_exp0, sub_mant, norm_mant); - let exp_fin = self.s.m.select(c, is_exp0, sub_exp, norm_exp); - - let mant_bits = self.s.m.select(c, is_special, bits, mant_fin); - let exp = self.s.m.select(c, is_special, k0, exp_fin); - (self.as_float(mant_bits), exp) - } - // ---- lane booleans ---- fn boolean(&mut self, b: Bool, at: usize) -> Result { @@ -3987,25 +3474,8 @@ impl<'a> Lower<'a> { return Ok(self.s.m.bool(b == Bool::TRUE)); } if let Some(&v) = self.bools.get(&(at, b)) { - if let Some(deps) = self.bool_deps.get(&(at, b)) { - let deps = deps.clone(); - self.extend_cur_reads(&deps); - } return Ok(v); } - let saved = std::mem::take(&mut self.cur_reads); - let r = self.boolean_uncached(b, at); - let sub = std::mem::replace(&mut self.cur_reads, saved); - let v = r?; - self.extend_cur_reads(&sub); - if !sub.is_empty() { - self.bool_deps.insert((at, b), sub); - } - self.bools.insert((at, b), v); - Ok(v) - } - - fn boolean_uncached(&mut self, b: Bool, at: usize) -> Result { let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant"); let a = self.atom(atom, at)?; let m = &mut self.s.m; @@ -4029,21 +3499,18 @@ impl<'a> Lower<'a> { self.s.m.select(at, a, h, l) } }; + self.bools.insert((at, b), v); Ok(v) } fn atom(&mut self, atom: Atom, at: usize) -> Result { match atom { - Atom::Lane(v) => { - let r = self.lane_bits.get(&v).copied().ok_or_else(|| { - self.lane_fail - .get(&v) - .copied() - .unwrap_or("a lane mask from a carry") - })?; - self.record_read(v); - Ok(r) - } + Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| { + self.lane_fail + .get(&v) + .copied() + .unwrap_or("a lane mask from a carry") + }), Atom::Uniform(v) => match self.get(v)? { Val::Bit(x) => Ok(x), Val::I32(x) => { @@ -4086,12 +3553,6 @@ impl<'a> Lower<'a> { let hi = hi.map(word).transpose()?; Ok(self.lane_bit(at, lo, hi)) } - Atom::Constant(0) => Ok(self.s.m.bool(false)), - Atom::Constant(k) - if k == u64::MAX || (!self.x.native.wave64 && k as u32 == u32::MAX) => - { - Ok(self.s.m.bool(true)) - } Atom::Constant(k) if self.console_lanes => { let lo = self.s.m.i32(k as u32); let hi = self.s.m.i32((k >> 32) as u32); @@ -4102,62 +3563,6 @@ impl<'a> Lower<'a> { } } - /// The mask operand of a select or carry-in as a per-lane boolean: a - /// tracked mask, this lane's bit of an untracked SGPR mask (console - /// lanes only), or an inline constant. - fn mask_cond( - &mut self, - inst: &Inst, - op: Option<&Operand>, - at: usize, - err: Why, - ) -> Result { - match op { - Some(&Operand::Scalar { code, .. }) => { - if let Some(m) = inst.read(Reg::S(code)).and_then(|m| { - self.x - .st - .masks - .get(&m) - .or_else(|| self.x.st.other.get(&m)) - .copied() - }) { - return self.boolean(m, at); - } - if !self.console_lanes { - return Err(err); - } - let lo = inst.read(Reg::S(code)).ok_or(err)?; - let lo = self.i32_of(lo)?; - let hi = if self.x.native.wave64 { - match inst.read(Reg::S(code + 1)) { - Some(v) => Some(self.i32_of(v)?), - None => Some(self.s.m.i32(0)), - } - } else { - None - }; - self.s.flags |= flags::WAVE_OPS; - Ok(self.lane_bit(at, lo, hi)) - } - Some(&Operand::Const(k)) => { - let x = crate::resource::inline(k).ok_or(err)?; - if x == 0 { - Ok(self.s.m.bool(false)) - } else if x == u32::MAX { - Ok(self.s.m.bool(true)) - } else if self.console_lanes { - let lo = self.s.m.i32(x); - let hi = self.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }); - Ok(self.lane_bit(at, lo, Some(hi))) - } else { - Err(err) - } - } - _ => Err(err), - } - } - /// A console wave64 program in host waves of 32: the first console thread of this host wave /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread @@ -4175,22 +3580,13 @@ impl<'a> Lower<'a> { let zero = self.s.m.i32(0); self.s.m.store(e, ptr, zero); self.group_sync(e); - let lane = self - .s - .op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let first = self.s.m.cmp(e, pred::EQ, lane, zero); let k32 = self.s.m.i32(32); let add = self.s.m.select(e, first, k32, zero); let ptr = self.s.m.element(e, lds, k); let old = self.s.m.atomic(e, Rmw::Add, ptr, add); - let base = self.s.op( - e, - "waveReadLaneFirst.i32", - Attr::NoUnwind, - i32t, - 118, - &[old], - ); + let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]); self.s.flags |= flags::WAVE_OPS; self.wave_base = Some(base); Some(base) @@ -4200,28 +3596,12 @@ impl<'a> Lower<'a> { /// (host waves of 32), else the wave's first thread index rounded down plus the lane. fn console_thread(&mut self) -> V { let (e, i32t) = (self.s.entry, self.s.t.i32); - let lane = self - .s - .op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); if let Some(base) = self.wave_base() { return self.s.m.bin(e, Bin::Add, base, lane); } - let flat = self.s.op( - e, - "flattenedThreadIdInGroup.i32", - Attr::ReadNone, - i32t, - 96, - &[], - ); - let first = self.s.op( - e, - "waveReadLaneFirst.i32", - Attr::NoUnwind, - i32t, - 118, - &[flat], - ); + let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]); + let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]); let wave = self.s.wave_size.unwrap_or(32); let mask = self.s.m.i32(!(wave - 1)); let base = self.s.m.bin(e, Bin::And, first, mask); @@ -4251,8 +3631,7 @@ impl<'a> Lower<'a> { fn group_sync(&mut self, block: usize) { let mode = self.s.m.i32(meeting_mode()); let void = self.s.t.void; - self.s - .op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + self.s.op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]); } /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get @@ -4339,9 +3718,7 @@ impl<'a> Lower<'a> { }; let bit = self.boolean(m, at)?; let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); - let some = self - .s - .op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]); + let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]); self.s.flags |= flags::WAVE_OPS; if !self.exchange.as_ref().is_some_and(|e| !e.1) { return Ok(some); @@ -4359,19 +3736,8 @@ impl<'a> Lower<'a> { fn wave_wide(&mut self, b: usize, when: Bool) -> Result { const WHY: Why = "a wave-wide branch where not every lane runs"; - let any = self - .x - .st - .wave_any - .get(b) - .copied() - .flatten() - .ok_or("a wave-wide branch on a scalar condition")?; - if self.exchange.is_none() - && self.halves.is_none() - && self.console_lanes - && self.mask_data == MaskData::Console - { + let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?; + if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console { // The host's waves are the console's: the wave's own answer. The lanes that are // elsewhere have no bit set, as on the console, so "some lane" needs no one but // the lanes here, and "every lane's bit is clear" is true of the others anyway. @@ -4379,11 +3745,7 @@ impl<'a> Lower<'a> { let mine = self.boolean(when, c)?; let i1t = self.s.t.i1; self.s.flags |= flags::WAVE_OPS; - let (name, code) = if any { - ("waveAnyTrue", 113) - } else { - ("waveAllTrue", 114) - }; + let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) }; return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine])); } if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) { @@ -4405,26 +3767,19 @@ impl<'a> Lower<'a> { self.s.m.bin(c, Bin::Xor, mine, t) }; let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); - let some = self - .s - .op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]); + let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]); self.s.flags |= flags::WAVE_OPS; let some = self.s.m.cast(c, Cast::ZExt, some, i32t); let (lo, hi) = self.exchange_halves(c, some); let c = self.cur; let both = self.s.m.bin(c, Bin::Or, lo, hi); let z = self.s.m.i32(0); - Ok(self - .s - .m - .cmp(c, if any { pred::NE } else { pred::EQ }, both, z)) + Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z)) } /// Whether every lane runs IR block `b` (always true without `exchange`). fn all_lanes(&self, b: usize) -> bool { - self.exchange - .as_ref() - .is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false)) + self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false)) } /// This lane's bit of the mask `lo`, `hi` (wave64). @@ -4433,14 +3788,7 @@ impl<'a> Lower<'a> { let lane = if self.exchange.is_some() { self.console_lane() } else { - self.s.op( - at, - "waveGetLaneIndex", - Attr::ReadOnly, - self.s.t.i32, - 111, - &[], - ) + self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[]) }; let (k31, k32, one, z) = ( self.s.m.i32(31), @@ -4522,8 +3870,14 @@ impl<'a> Lower<'a> { let Some(new) = inst.write(reg) else { return }; let x = match (guard, reg) { (Some(g), Reg::V(_)) => { - let old = self.old_i32_of(inst.read(reg), true, None); - self.s.m.select(self.cur, g, x, old) + let old = match inst.read(reg).map(|o| self.i32_of(o)) { + Some(Ok(o)) => o, + // The validator refuses reads of undef. + _ => self.s.m.i32(0), + }; + let v = self.s.m.select(self.cur, g, x, old); + self.s.m.tag(v, Tag::Guard); + v } _ => x, }; @@ -4559,7 +3913,10 @@ impl<'a> Lower<'a> { if unused != 2 { return field; } - let old = self.old_i32_of(inst.read(reg), false, None); + let old = match inst.read(reg).map(|o| self.i32_of(o)) { + Some(Ok(o)) => o, + _ => self.s.m.i32(0), + }; let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at)); let old = self.s.m.bin(c, Bin::And, old, keep); self.s.m.bin(c, Bin::Or, old, field) @@ -4640,75 +3997,11 @@ impl<'a> Lower<'a> { .collect() } - /// An image atomic DXIL has no operation for (`inc`, `dec`, `fcmpswap`, - /// `fmin`, `fmax`), on the dword at `coords` of the 32-bit integer view - /// `h`: a compare-and-swap loop from a first guess of 0, until the - /// exchange finds the value the new one was made from (a null view reads - /// 0, so it leaves at once). `vals`: the data (fcmpswap: new, compare). - /// Returns the old value. - #[allow(dead_code)] - fn atomic_loop(&mut self, h: V, coords: &[V], op: &str, vals: &[V]) -> V { - let i32t = self.s.t.i32; - let entry = self.cur; - let (head, done) = (self.s.m.new_block(), self.s.m.new_block()); - self.s.m.terminate(entry, Term::Br(head)); - self.cur = head; - let old = self.s.m.phi(head, i32t); - let (data, zero, one) = (vals[0], self.s.m.i32(0), self.s.m.i32(1)); - let new = match op { - // old >= data ? 0 : old + 1 - "inc" => { - let up = self.s.m.bin(head, Bin::Add, old, one); - let wrap = self.s.m.cmp(head, pred::IUGE, old, data); - self.s.m.select(head, wrap, zero, up) - } - // old == 0 || old > data ? data : old - 1 - "dec" => { - let down = self.s.m.bin(head, Bin::Sub, old, one); - let empty = self.s.m.cmp(head, pred::EQ, old, zero); - let over = self.s.m.cmp(head, pred::IUGT, old, data); - let reload = self.s.m.bin(head, Bin::Or, empty, over); - self.s.m.select(head, reload, data, down) - } - // A float compare: -0 matches +0, NaN matches nothing. - "fcmpswap" => { - let (o, c) = (self.as_float(old), self.as_float(vals[1])); - let eq = self.s.m.cmp(head, pred::OEQ, o, c); - self.s.m.select(head, eq, data, old) - } - // As v_min_f32 and v_max_f32. - _ => { - let (d, o) = (self.as_float(data), self.as_float(old)); - let m = self.binary(if op == "fmax" { 35 } else { 36 }, d, o); - self.as_int(m) - } - }; - let mut args = vec![h]; - args.extend_from_slice(coords); - args.extend([old, new]); - let prev = self.s.op( - head, - "atomicCompareExchange.i32", - Attr::NoUnwind, - i32t, - 79, - &args, - ); - let found = self.s.m.cmp(head, pred::EQ, prev, old); - self.s.m.terminate(head, Term::CondBr(found, done, head)); - self.s.m.set_phi(old, vec![(zero, entry), (prev, head)]); - self.cur = done; - prev - } - - fn is_mesh(&self) -> bool { - self.s.mesh.is_some() || self.mesh_emu.is_some() - } /// Code that depends on the lane layout: wave operations, and in compute /// the console's wave size (lanes are thread ids in group order there). /// Pixel lanes match only within a quad. fn cross_lane(&mut self, quad: bool) -> Result<(), Why> { - if self.is_mesh() { + if self.s.mesh.is_some() { // shortcut: no wave size for mesh shaders in SM 6.6, so host // lanes cannot follow the console's; emulate through group-shared // memory if mesh programs turn out to need these. @@ -4881,7 +4174,7 @@ impl<'a> Lower<'a> { } fn lane_index(&mut self) -> V { - if self.is_mesh() { + if self.s.mesh.is_some() { // The console's lane: mesh code reads no other lanes, so host // waves need not match the console's. let f = self.mesh_thread(); @@ -4922,33 +4215,6 @@ impl<'a> Lower<'a> { r } - /// The x then y gradients (three each, undefined past `coords`) of - /// float coordinates `coords` across this lane's quad: lane 1 less lane - /// 0, lane 2 less lane 0, as the hardware's coarse derivatives. - #[allow(dead_code)] - fn quad_gradients(&mut self, coords: &[V]) -> Vec { - self.s.flags |= flags::WAVE_OPS; - let c = self.cur; - let fu = self.s.m.undef(self.s.t.f32); - let lane = self.lane_index(); - let (not3, one, two) = (self.s.m.i32(!3), self.s.m.i32(1), self.s.m.i32(2)); - let base = self.s.m.bin(c, Bin::And, lane, not3); - let right = self.s.m.bin(c, Bin::Or, base, one); - let below = self.s.m.bin(c, Bin::Or, base, two); - let mut g = vec![fu; 6]; - for (k, &x) in coords.iter().enumerate().take(3) { - let xi = self.as_int(x); - let at = |l: &mut Self, lane: V| { - let v = l.read_lane(xi, lane); - l.as_float(v) - }; - let (x0, x1, x2) = (at(self, base), at(self, right), at(self, below)); - g[k] = self.s.m.bin(c, Bin::Sub, x1, x0); - g[3 + k] = self.s.m.bin(c, Bin::Sub, x2, x0); - } - g - } - /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here. @@ -4956,34 +4222,24 @@ impl<'a> Lower<'a> { let c = self.cur; let i32t = self.s.t.i32; self.s.flags |= flags::WAVE_OPS; - let first = self - .s - .op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]); + let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]); let Some(g) = guard else { return (first, self.s.m.bool(true)); }; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); - let r = self - .s - .op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]); + let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]); let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1)); let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32)); // FirstbitLo (dx.op 32): the lowest set bit - let flo = self - .s - .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]); - let fhi = self - .s - .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]); + let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]); + let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]); let fhi = self.s.m.bin(c, Bin::Add, fhi, k32); let in_lo = self.s.m.cmp(c, pred::NE, lo, z); let in_hi = self.s.m.cmp(c, pred::NE, hi, z); let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi); let lane = self.s.m.select(c, in_lo, flo, fhi); // no lane in EXEC: read this lane (one that is here); the read is not used - let me = self - .s - .op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let lane = self.s.m.select(c, any, lane, me); let at = self.read_lane(x, lane); (self.s.m.select(c, any, at, first), any) @@ -5003,7 +4259,6 @@ impl<'a> Lower<'a> { /// The float value of a register value. fn float_of(&mut self, v: Value) -> Result { if let Some(&f) = self.floats.get(&v) { - self.record_read(v); return Ok(f); } let x = self.i32_of(v)?; @@ -5054,7 +4309,7 @@ impl<'a> Lower<'a> { || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4; // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the // console's, so quad-local swizzles read through quad operations. - let mesh_quad = self.is_mesh() && quad; + let mesh_quad = self.s.mesh.is_some() && quad; if !mesh_quad { self.cross_lane(quad)?; } @@ -5092,8 +4347,8 @@ impl<'a> Lower<'a> { if name == "ds_bpermute_b32" { // Backward permute: no LDS is touched. Each lane takes the data // register of the lane its address names, (address + offset) / 4 - // within the wave; a source lane outside EXEC gives 0. (Grand - // Theft Auto VI's checkerboard shadow-mask generators read their + // within the wave; a source lane outside EXEC gives 0. ( + // the title's checkerboard shadow-mask generators read their // neighbours' samples with it; without them every shadowed light // was multiplied by an empty mask.) // shortcut: a source lane that is not at this instruction on the @@ -5253,12 +4508,7 @@ impl<'a> Lower<'a> { } if let Some(rest) = name.strip_prefix("ds_write") { let elements = if rest.starts_with('2') { - let mut elements = pair(name); - // Equal offsets perform one write with DATA0 (RDNA 2 ISA §10.4.3). - if offset0 == offset1 { - elements.truncate(1); - } - elements + pair(name) } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { vec![(offset, width(name))] } else { @@ -5304,9 +4554,10 @@ impl<'a> Lower<'a> { Some(d) => Some(self.vgprs(inst, d, 1)?[0]), None => None, }; - let outside = match (guard, dst_reg.and_then(|r| inst.read(Reg::V(r)))) { - (Some(_), Some(v)) => self.old_i32_of(Some(v), true, None), - _ => self.s.m.i32(0), + let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v))); + let outside = match old_reg { + Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)), + None => self.s.m.i32(0), }; let p = dword(self, offset); if let Some(max) = match op.as_str() { @@ -5427,9 +4678,6 @@ impl<'a> Lower<'a> { let inst: &'a Inst = &self.x.p.blocks[b].insts[i]; let offset = inst.machine.offset; let name = inst.name(); - self.cur_reads.clear(); - self.cur_old_deps.clear(); - self.cur_edge = None; self.local_ok = name.starts_with("s_bcnt1_i32_") || name.starts_with("s_ff1_i32_") || name.starts_with("v_mbcnt_"); @@ -5466,8 +4714,7 @@ impl<'a> Lower<'a> { // half wrote is visible, and what it still reads is not overwritten let mode = self.s.m.i32(meeting_mode()); let void = self.s.t.void; - self.s - .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); } let r = match &inst.fields { Fields::Sop { .. } => self.sop(inst), @@ -5503,7 +4750,9 @@ impl<'a> Lower<'a> { // program where its results are needed, and two trace programs // came out without their test that way. Fields::Image { .. } if name.starts_with("image_bvh") => { - return self.bvh(inst, b, i).map_err(|why| unsupported(offset, why)); + return self + .bvh(inst, b, i) + .map_err(|why| unsupported(offset, why)); } Fields::Image { .. } => self.image(inst, b, i), Fields::Buffer { .. } => self.buffer(inst, b, i), @@ -5512,66 +4761,8 @@ impl<'a> Lower<'a> { Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i), Fields::Flat { .. } => Err("flat memory"), }; - let reads = std::mem::take(&mut self.cur_reads); - let old_deps = std::mem::take(&mut self.cur_old_deps); match r { - Ok(()) => { - let guard = self.x.st.guards[b][i]; - if !reads.is_empty() { - if effect { - self.sinks.push(SinkRead { - block: b, - guard, - offset, - deps: reads, - }); - } else { - let use_guard = matches!( - &inst.fields, - Fields::Valu(v) - if v.dpp.is_none() - && !matches!( - name, - "v_readfirstlane_b32" - | "v_readlane_b32" - | "v_writelane_b32" - ) - ) - .then_some(guard) - .flatten(); - for &(_, w) in &inst.writes { - if matches!(self.vals.get(&w), Some(Val::I32(_) | Val::Bit(_))) - || self.lane_bits.contains_key(&w) - { - self.record_write_deps(w, b, use_guard, false, None, reads.clone()); - } - } - } - } - for old in old_deps { - for &(_, w) in &inst.writes { - if !matches!(self.vals.get(&w), Some(Val::I32(_) | Val::Bit(_))) { - continue; - } - if let Some(why) = old.direct_why { - self.taint_candidates.insert(w); - self.direct_missing - .push((w, why, b, guard, old.invert_guard)); - } - if let Some(u) = old.value { - self.record_write_deps( - w, - b, - guard, - old.invert_guard, - old.ignore_why, - vec![ReadDep::Value(u)], - ); - } - } - } - Ok(()) - } + Ok(()) => Ok(()), Err(why) if effect => Err(unsupported(offset, why)), Err(why) => { for &(_, v) in &inst.writes { @@ -5587,8 +4778,7 @@ impl<'a> Lower<'a> { fn lds_meeting(&mut self) { let mode = self.s.m.i32(meeting_mode()); let void = self.s.t.void; - self.s - .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); } /// Whether `v` is a register no program reads as a number: a descriptor dword without @@ -5663,10 +4853,7 @@ impl<'a> Lower<'a> { let Fields::Valu(f) = &cmp.fields else { return false; }; - if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") - || f.sdwa.is_some() - || f.dpp.is_some() - { + if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") || f.sdwa.is_some() || f.dpp.is_some() { return false; } let lanes = f.src.iter().find_map(|o| match *o { @@ -5954,7 +5141,7 @@ impl<'a> Lower<'a> { } let m = &mut self.s.m; let _ = m; - let (r, scc_value): (V, Option) = match name { + let (r, carry): (V, Option) = match name { "s_mov_b32" => (src32(self, 0)?, None), "s_movk_i32" => (sext16(self), None), "s_cselect_b32" => { @@ -5982,22 +5169,18 @@ impl<'a> Lower<'a> { src32(self, 1)? }; let r = self.s.m.bin(c, Bin::Add, a, b); - let flag = if name == "s_add_u32" { - self.s.m.cmp(c, pred::IULT, r, a) + let carry = if name == "s_add_u32" { + Some(self.s.m.cmp(c, pred::IULT, r, a)) } else { - self.signed_overflow(c, a, b, r, false) + None }; - (r, Some(flag)) + (r, carry) } "s_sub_u32" | "s_sub_i32" => { let (a, b) = (src32(self, 0)?, src32(self, 1)?); let r = self.s.m.bin(c, Bin::Sub, a, b); - let flag = if name == "s_sub_u32" { - self.s.m.cmp(c, pred::IULT, a, b) - } else { - self.signed_overflow(c, a, b, r, true) - }; - (r, Some(flag)) + let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b)); + (r, carry) } "s_addc_u32" | "s_subb_u32" => { let (a, b) = (src32(self, 0)?, src32(self, 1)?); @@ -6127,7 +5310,7 @@ impl<'a> Lower<'a> { }; self.set(lo, Val::I32(r)); if let Some(scc) = scc { - let val = match scc_value { + let val = match carry { Some(k) => Val::Bit(k), None if matches!( name, @@ -6141,6 +5324,9 @@ impl<'a> Lower<'a> { { return Ok(()); } + None if name.starts_with("s_add") || name.starts_with("s_sub") => { + Val::Missing("the carry of a scalar operation") + } None => { let z = self.s.m.i32(0); Val::Bit(self.s.m.cmp(c, pred::NE, r, z)) @@ -6151,18 +5337,6 @@ impl<'a> Lower<'a> { Ok(()) } - /// RDNA2 sets SCC on signed overflow. The result changes the first - /// operand's sign when matching signs are added or opposite signs are - /// subtracted. Test the sign bit of both XORs without widening. - fn signed_overflow(&mut self, c: usize, a: V, b: V, result: V, subtract: bool) -> V { - let m = &mut self.s.m; - let sign_change = m.bin(c, Bin::Xor, a, result); - let sign_check = m.bin(c, Bin::Xor, if subtract { a } else { result }, b); - let overflow_bits = m.bin(c, Bin::And, sign_change, sign_check); - let zero = m.i32(0); - m.cmp(c, pred::SLT, overflow_bits, zero) - } - /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the /// scalar and vector add-with-carry instructions set it. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option) -> (V, V) { @@ -6210,24 +5384,10 @@ impl<'a> Lower<'a> { if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) { return self.code_smem(inst, a); } - if self.is_global(site) { - return self.global_smem(inst); - } if self.scalar.get(&site).is_some_and(|a| a.param == MEMORY) { return self.memory_smem(inst); } let Some(rest) = name.strip_prefix("s_buffer_load_dword") else { - if let Some(a) = self.scalar.get(&site).copied() - && self - .x - .native - .layout - .get(a.param) - .is_some_and(|p| p.root == RootType::Descriptor) - && !self.loads_descriptor(site) - { - return self.root_view_smem(inst, a, site); - } return self.descriptor_data(inst, site); }; let count = match rest { @@ -6273,46 +5433,14 @@ impl<'a> Lower<'a> { // heap holds a buffer view there, not a constant buffer: read as // raw bytes, as a table's SRV is below. Read as a constant buffer // (the host's validation: "Descriptor Type in Heap: SRV, Register - // Type: CBV", heap index 17) the loads gave nothing: Grand Theft - // Auto VI's meshlet culling (BatchCullMeshlets, + // Type: CBV", heap index 17) the loads gave nothing: + // the title's meshlet culling (BatchCullMeshlets, // BatchCullPreSkinnedMeshlets, BatchCullBatchCSMeshlets) reads its // batch records, mesh headers and instance transforms this way, so // it passed no meshlet and every indirect mesh draw ran empty. // The host's table of strides by heap slot tells a buffer view // (not 0) from anything else, which is still read as a constant // buffer; only the load that fits the slot runs. - // A raw view for an SRV range. A descriptor of no listed kind (one - // fetched from the heap by index) that vector buffer accesses use is - // a buffer view in the title's heap too: an SRV if they only read - // it, a UAV if one writes it. Reading either slot through a - // constant buffer handle is a descriptor of the wrong type. - let raw = match kind.map(|u| u.kind) { - Some(ResourceType::Srv) => Some(11), - Some(ResourceType::Uav) => Some(11 | 0x1000), - None => self.heap_buffer_view(src), - _ => None, - }; - if let Some(props) = raw { - let h = self.handle(site, src, false, (props, 0))?; - for k in 0..count { - let off = self.s.m.i32(4 * k); - let a = self.s.m.bin(c, Bin::Add, addr, off); - let mask = self.s.m.i8(1); - let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); - let r = self.s.op( - c, - "rawBufferLoad.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 139, - &[h, a, u, mask, al], - ); - let x = self.s.m.extract(c, r, 0); - let x = self.as_int(x); - self.write(inst, Reg::S(code + k as u8), x, None); - } - return Ok(()); - } let picked = match kind { None => self.slot_stride(src)?, Some(_) => None, @@ -6434,9 +5562,7 @@ impl<'a> Lower<'a> { // shortcut: the base level reads 0 (the host view starts at its own // level 0, so sizes the code shifts by it come out right) and the other // dwords (addresses, formats, tiling) have no host value: reading them - // stops the program. So does reading any dword of a descriptor that - // scalar buffer loads use first; its reasons name the dword and the - // view's kind. + // stops the program. fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { const OTHER: Why = "a descriptor's address or format read as data"; let Fields::Smem { @@ -6444,7 +5570,7 @@ impl<'a> Lower<'a> { .. } = inst.fields else { - return Err(smem_reason(inst.name())); + return Err("a scalar memory read as data"); }; let count = match inst.name().strip_prefix("s_load_dword") { Some("") => 1u32, @@ -6452,7 +5578,7 @@ impl<'a> Lower<'a> { Some("x4") => 4, Some("x8") => 8, Some("x16") => 16, - _ => return Err(smem_reason(inst.name())), + _ => return Err("a scalar memory read as data"), }; // How the program uses the descriptor tells the view's kind: an image or buffer // instruction before a scalar buffer load, which reads any buffer. @@ -6469,13 +5595,10 @@ impl<'a> Lower<'a> { }) }) }; - let by_scalar_load = - |u: &(Site, u8)| matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. }); - let use_of = |of: Site| { - uses(of) - .find(|u| !by_scalar_load(u)) - .or_else(|| uses(of).next()) + let by_scalar_load = |u: &(Site, u8)| { + matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. }) }; + let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next()); // The console compiler loads a descriptor again wherever it needs it, and for a // size it reads the dwords of a load that nothing uses as a descriptor (a texture // picked from the heap by an index held per lane: one load for its width, one for @@ -6513,10 +5636,9 @@ impl<'a> Lower<'a> { // descriptor's address or format is. let sampler = x.res.descriptors.iter().any(|d| { d.role == Role::Sampler - && d.source - .leaves() - .into_iter() - .any(|l| matches!(*l, Source::Loaded { load, .. } if load == site)) + && d.source.leaves().into_iter().any( + |l| matches!(*l, Source::Loaded { load, .. } if load == site), + ) }); if sampler { self.stale.extend(inst.writes.iter().map(|w| w.1)); @@ -6543,12 +5665,14 @@ impl<'a> Lower<'a> { } return Ok(()); } - if let Ok(words) = self.descriptor_words(site, count) { - // No access names it: the console words are all there is. - for (k, x) in words.into_iter().enumerate() { - self.write(inst, Reg::S(code + k as u8), x, None); - } - return Ok(()); + if std::env::var_os("VICTORY_DESC_WHY").is_some() { + eprintln!( + "DESC-WHY {:#x} {} scalar={:?} lane_copied={}", + inst.machine.offset, + inst.name(), + address, + self.x.res.lane_copied.contains(&site) + ); } return Err("a descriptor read only as data"); }; @@ -6591,38 +5715,14 @@ impl<'a> Lower<'a> { } (props, None) } + // Read by scalar buffer loads alone: the raw view `smem` reads it through. + Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => { + ((11, 0), None) + } + // A constant buffer: nothing of its descriptor is a number. Fields::Smem { .. } => { - // Scalar buffer loads (`s_buffer_load_dword*`) read through - // it first. Each dword gets the reason for what it holds, - // as an error here would give every dword one reason. - let vector_later = uses(site) - .filter(|u| !by_scalar_load(u)) - .any(|(s, _)| s != at); - let records = match used.map(|u| (u.kind, u.stride)) { - _ if vector_later => { - "a descriptor read as data, used by scalar loads before a vector access" - } - Some((ResourceType::Srv, 0)) => { - "a scalar-loaded raw buffer's record count read as data" - } - Some((ResourceType::Srv, _)) => { - "a scalar-loaded structured buffer's record count read as data" - } - Some((ResourceType::Cbv, _)) => { - "a scalar-loaded constant buffer's record count read as data" - } - _ => "a scalar-loaded buffer's record count read as data", - }; - for k in 0..count { - let why = match k.wrapping_sub(u32::from(first)) { - 2 => records, - _ => "a scalar-loaded buffer's address or format read as data", - }; - if let Some(v) = inst.write(Reg::S(code + k as u8)) { - self.vals.insert(v, Val::Missing(why)); - } - } - return Ok(()); + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a constant buffer's descriptor read as data"); } _ => return Err("a scalar memory read as data"), }; @@ -6702,24 +5802,13 @@ impl<'a> Lower<'a> { words } }; - // Fields the host view gives are rebuilt from it; the console's - // other words (addresses, formats) come from the descriptor words, - // when those are already bound for this program. - let console = self - .s - .descriptor_words - .is_some() - .then(|| self.descriptor_words(site, count).ok()) - .flatten(); for k in 0..count { let rel = k.wrapping_sub(u32::from(first)); - match (words.iter().find(|w| w.0 == rel), &console) { - (Some(&(_, x)), _) => self.write(inst, Reg::S(code + k as u8), x, None), - (None, Some(c)) => self.write(inst, Reg::S(code + k as u8), c[k as usize], None), - (None, None) => { + match words.iter().find(|w| w.0 == rel) { + Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None), + None => { if let Some(v) = inst.write(Reg::S(code + k as u8)) { - let why = descriptor_field(image.is_some(), rel).unwrap_or(OTHER); - self.vals.insert(v, Val::Missing(why)); + self.vals.insert(v, Val::Missing(OTHER)); self.stale.insert(v); } } @@ -6728,71 +5817,14 @@ impl<'a> Lower<'a> { Ok(()) } - /// The use site and first dword of a resource descriptor loaded from - /// the same heap entry as the scalar load at `site`: the same parameter - /// and offset, and the same computed term (or the first lane's value of - /// the same VGPR, in another pass of a waterfall loop). - #[allow(dead_code)] - fn same_entry_use(&self, site: Site) -> Option<(Site, u8)> { - let a = self.scalar.get(&site)?; - let lane = |v: Value| -> Value { - self.x - .p - .blocks - .iter() - .flat_map(|b| &b.insts) - .find(|i| i.writes.iter().any(|w| w.1 == v)) - .filter(|i| i.name() == "v_readfirstlane_b32") - .and_then(|i| i.reads.iter().find(|r| matches!(r.0, Reg::V(_)))) - .map_or(v, |r| r.1) - }; - let same = |b: &Address| { - b.param == a.param - && b.offset == a.offset - && match (a.dynamic, b.dynamic) { - (None, None) => true, - (Some(x), Some(y)) => x == y || lane(x) == lane(y), - _ => false, - } - }; - self.x - .res - .descriptors - .iter() - .filter(|d| d.role == Role::Resource) - .find_map(|d| { - d.source.leaves().into_iter().find_map(|l| match *l { - Source::Loaded { load, first } - if load != site && self.scalar.get(&load).is_some_and(same) => - { - Some((d.site, first)) - } - _ => None, - }) - }) - } - - /// Whether a descriptor the program uses comes from the scalar load at - /// `site` (a descriptor in memory, not data). - fn loads_descriptor(&self, site: Site) -> bool { - self.x.res.descriptors.iter().any(|d| { - d.source.leaves().into_iter().any(|l| { - matches!(*l, Source::Loaded { load, .. } | Source::Fetched { load, .. } - if load == site) - }) - }) - } - - /// `s_load_dword*` from a root view's address: that buffer's memory, as - /// global loads from it read it (a root SRV raw, a root CBV as a - /// constant buffer). - fn root_view_smem(&mut self, inst: &Inst, a: Address, site: Site) -> Result<(), Why> { + /// `s_load_dword*` from the program's constant table. + fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> { let Fields::Smem { data: Some(Operand::Scalar { code, .. }), .. } = inst.fields else { - return Err(smem_reason(inst.name())); + return Err("a scalar load"); }; let count = match inst.name().strip_prefix("s_load_dword") { Some("") => 1u32, @@ -6800,94 +5832,23 @@ impl<'a> Lower<'a> { Some("x4") => 4, Some("x8") => 8, Some("x16") => 16, - _ => return Err(smem_reason(inst.name())), + _ => return Err("a scalar load from the code"), }; let c = self.cur; - let mut off = self.s.m.i32(a.offset); + let mut addr = self.s.m.i32(a.offset); if let Some(value) = a.dynamic { let mut d = self.i32_of(value)?; // A term held per lane reached the address through // `v_readfirstlane_b32`: the first lane's. let per_lane = self.def_block.get(&value).is_some_and(|&b| { - let writes = |i: &Inst| { - i.writes - .iter() - .any(|w| w.1 == value && matches!(w.0, Reg::V(_))) - }; + let writes = |i: &Inst| i.writes.iter().any(|w| w.1 == value && matches!(w.0, Reg::V(_))); self.x.p.blocks[b].insts.iter().any(writes) }); if per_lane { self.s.flags |= flags::WAVE_OPS; let i32t = self.s.t.i32; - d = self - .s - .op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]); + d = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]); } - off = self.s.m.bin(c, Bin::Add, off, d); - } - let src = Source::Built { - address: a, - bits: 0, - words: [0, 0], - }; - let raw = match self.used_kind(&src).map(|u| u.kind) { - Some(ResourceType::Srv) => true, - Some(ResourceType::Cbv) | None => false, - _ => return Err("a root UAV read with scalar loads"), - }; - let h = if raw { - self.handle(site, &src, false, (11, 0))? - } else { - self.handle(site, &src, false, (13, 0x1_0000))? - }; - for k in 0..count { - let four = self.s.m.i32(4 * k); - let at = self.s.m.bin(c, Bin::Add, off, four); - let x = if raw { - let (u, mask, al) = ( - self.s.m.undef(self.s.t.i32), - self.s.m.i8(1), - self.s.m.i32(4), - ); - let r = self.s.op( - c, - "rawBufferLoad.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 139, - &[h, at, u, mask, al], - ); - let x = self.s.m.extract(c, r, 0); - self.as_int(x) - } else { - self.cbuffer_dword(h, at) - }; - self.write(inst, Reg::S(code + k as u8), x, None); - } - Ok(()) - } - - /// `s_load_dword*` from the program's constant table. - fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> { - let Fields::Smem { - data: Some(Operand::Scalar { code, .. }), - .. - } = inst.fields - else { - return Err("a scalar load"); - }; - let count = match inst.name().strip_prefix("s_load_dword") { - Some("") => 1u32, - Some("x2") => 2, - Some("x4") => 4, - Some("x8") => 8, - Some("x16") => 16, - _ => return Err("a scalar load from the code"), - }; - let c = self.cur; - let mut addr = self.s.m.i32(a.offset); - if let Some(d) = a.dynamic { - let d = self.i32_of(d)?; addr = self.s.m.bin(c, Bin::Add, addr, d); } for k in 0..count { @@ -6926,44 +5887,15 @@ impl<'a> Lower<'a> { x } - /// Correctly rounded f32 bits of `value / (2^n - 1)`, for a signed or - /// unsigned integer already clamped to the normalized range. - fn norm_bits(&mut self, value: V, n: u32) -> V { - let c = self.cur; - // All normalized fields fit in signed i32 and convert to f32 exactly. - let f = self.s.m.cast(c, Cast::SiToFp, value, self.s.t.f32); - let bits = self.as_int(f); - if n == 1 { - return bits; - } - // Start at |value| / 2^n. In units of its last place, its magnitude - // is the 24-bit significand M. Multiplying by 2^n / (2^n - 1) - // adds M / (2^n - 1) ULPs. The denominator is odd, so rounding the - // correction has no ties. Only a full-scale input reaches the next - // exponent, and adding the correction to the bits carries into it. - let mask = self.s.m.i32(0x7f_ffff); - let implicit = self.s.m.i32(1 << 23); - let fraction = self.s.m.bin(c, Bin::And, bits, mask); - let significand = self.s.m.bin(c, Bin::Or, fraction, implicit); - let max = (1 << n) - 1; - let half = self.s.m.i32(max / 2); - let divisor = self.s.m.i32(max); - let biased = self.s.m.bin(c, Bin::Add, significand, half); - let correction = self.s.m.bin(c, Bin::UDiv, biased, divisor); - let scale = self.s.m.i32(n << 23); - let base = self.s.m.bin(c, Bin::Sub, bits, scale); - let rounded = self.s.m.bin(c, Bin::Add, base, correction); - let zero = self.s.m.i32(0); - let is_zero = self.s.m.cmp(c, pred::EQ, value, zero); - self.s.m.select(c, is_zero, zero, rounded) - } - /// `channels` channels of the element at byte `off` of raw buffer `h`, /// converted from the GFX10 buffer format `format` as the hardware's /// typed loads do (channels past the format's read 0, 0, 0, 1). // 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. + // 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. 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; @@ -7022,13 +5954,20 @@ impl<'a> Lower<'a> { }; let f32t = self.s.t.f32; let x = match numeric { - Numeric::Unorm => self.norm_bits(field, w), + Numeric::Unorm => { + let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); + let max = self.s.m.f32((((1u64 << w) - 1) as f32).to_bits()); + let q = self.s.m.bin(c, Bin::SDiv, f, max); + float(self, q) + } Numeric::Snorm => { let s = signed(self); - let min = self.s.m.i32(1u32.wrapping_sub(1 << (w - 1))); - let below = self.s.m.cmp(c, pred::SLT, s, min); - let clamped = self.s.m.select(c, below, min, s); - self.norm_bits(clamped, w - 1) + let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); + let max = self.s.m.f32((((1u64 << (w - 1)) - 1) as f32).to_bits()); + let q = self.s.m.bin(c, Bin::SDiv, f, max); + let lo = self.s.m.f32((-1.0f32).to_bits()); + let q = self.binary(35, q, lo); + float(self, q) } Numeric::Uscaled => { let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); @@ -7090,32 +6029,6 @@ impl<'a> Lower<'a> { } } - /// The raw view kind of descriptor `src` as vector buffer accesses use - /// it: an SRV (11) if they only read it, a UAV (`11 | 0x1000`) if one - /// writes through it (a store or an atomic), `None` if none uses it. - #[allow(dead_code)] - fn heap_buffer_view(&self, src: &Source) -> Option { - let mut view = None; - for (&((b, i), sampler), &other) in &self.descriptors { - if sampler || other != src { - continue; - } - let Some(inst) = self.x.p.blocks[b].insts.get(i) else { - continue; - }; - if !matches!(inst.fields, Fields::Buffer { .. }) { - continue; - } - let name = inst.name(); - if name.starts_with("buffer_load") || name.starts_with("tbuffer_load") { - view.get_or_insert(11); - } else { - return Some(11 | 0x1000); - } - } - view - } - /// For a root view the host binds as a raw view that may begin before /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add /// to offsets through it. Every root UAV, and the root SRVs of programs @@ -7192,22 +6105,11 @@ impl<'a> Lower<'a> { ) -> Result { match src { Source::Loaded { load, first } => { - let key = (self.cur, *load, *first, sampler, props.0, props.1); + let key = (self.cur, *load, *first, sampler, props); if let Some(&h) = self.handles.get(&key) { - if let Some(deps) = self.handle_deps.get(&key) { - let deps = deps.clone(); - self.extend_cur_reads(&deps); - } return Ok(h); } - let saved = std::mem::take(&mut self.cur_reads); - let index = self.heap_index(*load, *first, sampler); - let sub = std::mem::replace(&mut self.cur_reads, saved); - let index = index?; - self.extend_cur_reads(&sub); - if !sub.is_empty() { - self.handle_deps.insert(key, sub); - } + let index = self.heap_index(*load, *first, sampler)?; // A waterfall loop's load at the first lane's offset reads // each lane's own entry (see `resource::Waterfall`). let per_lane = self.x.res.waterfall.loads.contains(load); @@ -7222,16 +6124,19 @@ impl<'a> Lower<'a> { .get(..4) .and_then(|w| w.try_into().ok()) .ok_or("a sampler constant")?; - let comparison = props.0 & 0x8000 != 0; - let key = (words, comparison); - let n = match self.samplers.iter().position(|s| *s == key) { + let n = match self.samplers.iter().position(|w| *w == words) { Some(n) => n, None => { - self.samplers.push(key); + self.samplers.push(words); self.samplers.len() - 1 } }; - Ok(self.s.sampler_handle(self.cur, n as u32, comparison)) + if props.0 & 0x8000 != 0 { + // shortcut: one sampler used with and without comparison + // would need two static samplers; it becomes a comparison one. + self.s.cmp_samplers |= 1 << n; + } + Ok(self.s.sampler_handle(self.cur, n as u32)) } Source::Constant(_) => Err("a constant resource descriptor"), Source::Built { address, .. } => { @@ -7301,38 +6206,6 @@ impl<'a> Lower<'a> { } } - /// 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). - #[allow(dead_code)] - 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); - let here = std::mem::replace(&mut self.cur, at); - let prev_edge = self.cur_edge.replace((q, *block)); - let index = self.uniform_heap_index(arg, sampler); - self.cur_edge = prev_edge; - 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 a descriptor phi picks. Each predecessor computes its /// heap index at its end and the join picks one with a phi; a /// predecessor whose descriptor is itself chosen by control flow (a @@ -7361,10 +6234,9 @@ impl<'a> Lower<'a> { self.cur = here; index? } - Source::Phi { - block: inner, - args: inner_args, - } if depth > 0 => self.descriptor_phi(*inner, inner_args, sampler, depth - 1)?, + Source::Phi { block: inner, args: inner_args } if depth > 0 => { + self.descriptor_phi(*inner, inner_args, sampler, depth - 1)? + } _ => return Err(WHY), }; incoming.push((index, at)); @@ -7401,9 +6273,8 @@ impl<'a> Lower<'a> { // compute one too): a root view has no bounds of its own. let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1); let i32t = self.s.t.i32; - let slot = self - .s - .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]); + let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]); + self.s.m.tag(slot, Tag::Clamp); let two = self.s.m.i32(2); let byte = self.s.m.bin(c, Bin::Shl, slot, two); let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES); @@ -7471,9 +6342,7 @@ impl<'a> Lower<'a> { let index = match arg { Some(arg) => { let here = std::mem::replace(&mut self.cur, at); - let prev_edge = self.cur_edge.replace((q, *block)); let index = self.lane_heap_index(arg, sampler); - self.cur_edge = prev_edge; self.cur = here; index? } @@ -7621,7 +6490,7 @@ impl<'a> Lower<'a> { let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?; // Quad permutations and DPP8 stay in groups the pixel layout shares. let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. }); - let mesh_quad = self.is_mesh() && quad; + let mesh_quad = self.s.mesh.is_some() && quad; if !mesh_quad { self.cross_lane(quad)?; } @@ -7749,9 +6618,6 @@ impl<'a> Lower<'a> { if let Some(r) = self.valu16(inst, name, guard) { return r; } - if name == "v_pk_fmac_f16" { - return self.pk_fmac_f16(inst, guard); - } if let Some(op) = name.strip_prefix("v_pk_") { return self.packed16(inst, op, guard); } @@ -8105,9 +6971,8 @@ impl<'a> Lower<'a> { let r = self.s.m.select(c, make_zero, sign, signed_q); let r = self.s.m.select(c, make_inf, signed_inf, r); let r = self.s.m.select(c, invalid, kneg_qnan, r); - // denom's NaN quiets over num's (the hardware's priority). - let r = self.s.m.select(c, n_nan, n_qnan, r); let r = self.s.m.select(c, d_nan, d_qnan, r); + let r = self.s.m.select(c, n_nan, n_qnan, r); let rf = self.as_float(r); float(self, rf) } @@ -8117,7 +6982,13 @@ impl<'a> Lower<'a> { return Err("an accumulator"); }; let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?; - let acc = self.float_of(acc)?; + let acc = match self.floats.get(&acc) { + Some(&x) => x, + None => { + let x = self.i32_of(acc)?; + self.as_float(x) + } + }; let r = match name { "v_fmac_f32" => self.fmad(a, bb, acc), "v_mac_f32" => { @@ -8152,7 +7023,6 @@ impl<'a> Lower<'a> { let t = self.max_min(false, a, bb); self.max_min(false, t, cc) } - "v_div_fixup_f32" => self.div_fixup(a, bb, cc), _ => self.med3(a, bb, cc), }; float(self, r) @@ -8188,16 +7058,6 @@ impl<'a> Lower<'a> { }; float(self, r) } - "v_frexp_mant_f32" => { - let a = f(self, 0)?; - let (mant, _) = self.frexp_f32(a); - float(self, mant) - } - "v_frexp_exp_i32_f32" => { - let a = f(self, 0)?; - let (_, exp) = self.frexp_f32(a); - int(self, exp) - } "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => { let mut a = f(self, 0)?; if name == "v_cvt_rpi_i32_f32" { @@ -8231,9 +7091,7 @@ impl<'a> Lower<'a> { let x = s(self, 0)?; let (s1, s2) = (s(self, 1)?, s(self, 2)?); let i32t = self.s.t.i32; - let lane = self - .s - .op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let [k15, k8, k7, k2, k16, not31, not15] = [15, 8, 7, 2, 16, !31, !15].map(|x| self.s.m.i32(x)); let low = self.s.m.bin(c, Bin::And, lane, k15); @@ -8393,8 +7251,41 @@ impl<'a> Lower<'a> { float(self, r) } "v_cndmask_b32" => { - let cond = - self.mask_cond(inst, v.src.get(2), c, "a select on an untracked mask")?; + let mask = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), + _ => None, + }; + const UNTRACKED: Why = "a select on an untracked mask"; + let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) { + Some(m) => self.boolean(m, c)?, + // A mask the code holds as a number (a constant bit + // pattern: every other lane, every other pair...): + // this lane's bit of it. Exact where host lanes are + // the console's. + None if self.mask_data == MaskData::Console => { + // Each host wave taken as a wave of its own has no + // console lane numbers to pick the bits by. + if self.local { + return Err("a constant lane mask in a half-wave"); + } + let m = mask.ok_or(UNTRACKED)?; + let lo = self.i32_of(m).map_err(|_| UNTRACKED)?; + // wave64: the register after it holds lanes 32-63. + let high = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) if self.x.native.wave64 => { + Some(inst.read(Reg::S(code + 1)).ok_or(UNTRACKED)?) + } + _ => None, + }; + let hi = match high { + Some(h) => Some(self.i32_of(h).map_err(|_| UNTRACKED)?), + None => None, + }; + self.cross_lane(false)?; + self.lane_bit(c, lo, hi) + } + None => return Err(UNTRACKED), + }; if v.abs != 0 || v.neg != 0 { let (a, bb) = (f(self, 0)?, f(self, 1)?); let r = self.s.m.select(c, cond, bb, a); @@ -8412,12 +7303,14 @@ impl<'a> Lower<'a> { std::mem::swap(&mut a, &mut bb); } let cin = if name.ends_with("_ci_u32") { - Some(self.mask_cond( - inst, - v.src.get(2), - c, - "a carry-in from an untracked mask", - )?) + let m = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), + _ => None, + }; + let m = m + .and_then(|m| self.x.st.masks.get(&m).copied()) + .ok_or("a carry-in from an untracked mask")?; + Some(self.boolean(m, c)?) } else { None }; @@ -8527,55 +7420,51 @@ impl<'a> Lower<'a> { // two host waves that exchange: the console's first lane may be in the other // one, unless every lane holds the same value let alike = match v.src.first() { - Some(&Operand::Vector { reg, .. }) => inst - .read(Reg::V(reg)) - .is_some_and(|x| self.uniform.contains(&x)), + Some(&Operand::Vector { reg, .. }) => { + inst.read(Reg::V(reg)).is_some_and(|x| self.uniform.contains(&x)) + } _ => true, }; let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local; let r = if halves && !alike { if !self.all_lanes(self.cur_ir) { + // shortcut: `VICTORY_FIRSTLANE_OWN=1` takes the host wave's own + // first lane, exact when the value is the same in every lane of + // the console wave (the ray-tracing builder's scans read a sum of + // scalars this way, inside a loop whose exit is per console wave). + static OWN: std::sync::OnceLock = std::sync::OnceLock::new(); + if *OWN.get_or_init(|| std::env::var_os("VICTORY_FIRSTLANE_OWN").is_some_and(|v| v == "1")) { + return int(self, mine); + } need(self.cur_ir); return Err("a first-lane read where not every lane runs"); } let c = self.cur; - let i32t = self.s.t.i32; - let has = self.s.m.cast(c, Cast::ZExt, any, i32t); - let (lo_has, hi_has) = self.exchange_halves(c, has); - let (lo, hi) = self.exchange_halves(c, mine); - let z = self.s.m.i32(0); - let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z); - let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z); - // neither half has a lane in EXEC: the console reads lane 0 - let hi = self.s.m.select(c, in_hi, hi, lo); - self.s.m.select(c, in_lo, lo, hi) + if guard.is_none() && super::shader_opt() & super::bitcode::opt::FIRST != 0 { + // Every lane is in EXEC: the console's first lane is + // lane 0, which the lower half of every console wave + // has. No half needs to ask the other whether it has + // a lane (an exchange of the constant 1: two group + // barriers), and the lower half's value is the answer. + let (lo, _) = self.exchange_halves(c, mine); + lo + } else { + let i32t = self.s.t.i32; + let has = self.s.m.cast(c, Cast::ZExt, any, i32t); + let (lo_has, hi_has) = self.exchange_halves(c, has); + let (lo, hi) = self.exchange_halves(c, mine); + let z = self.s.m.i32(0); + let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z); + let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z); + // neither half has a lane in EXEC: the console reads lane 0 + let hi = self.s.m.select(c, in_hi, hi, lo); + self.s.m.select(c, in_lo, lo, hi) + } } else { mine }; int(self, r) } - "v_sad_u8" | "v_msad_u8" | "v_sad_u16" | "v_sad_u32" => { - if v.omod != 0 || v.abs != 0 || v.neg != 0 { - return Err("integer output modifiers"); - } - let (a, b, acc) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); - let delta = match name { - "v_sad_u8" | "v_msad_u8" => self.sad_lanes(a, b, 8, 4, name == "v_msad_u8"), - "v_sad_u16" => self.sad_lanes(a, b, 16, 2, false), - _ => self.abs_diff_u32(a, b), - }; - let mut r = self.s.m.bin(c, Bin::Add, acc, delta); - if v.clamp { - let over = self.s.m.cmp(c, pred::IULT, r, acc); - let max = self.s.m.i32(u32::MAX); - r = self.s.m.select(c, over, max, r); - } - let Some(Operand::Vector { reg, .. }) = v.dst else { - return Err("a result without a register"); - }; - self.write(inst, Reg::V(reg), r, guard); - Ok(()) - } _ => { let r = self.integer(inst, name)?; int(self, r) @@ -8583,49 +7472,6 @@ impl<'a> Lower<'a> { } } - /// `|a - b|` for unsigned 32-bit values. - fn abs_diff_u32(&mut self, a: V, b: V) -> V { - let c = self.cur; - let ab = self.s.m.bin(c, Bin::Sub, a, b); - let ba = self.s.m.bin(c, Bin::Sub, b, a); - let ge = self.s.m.cmp(c, pred::IUGE, a, b); - self.s.m.select(c, ge, ab, ba) - } - - /// Sum of unsigned absolute differences across `lanes` packed elements of - /// `bits` width (`8` or `16`). With `masked`, lanes where `a`'s element is - /// zero contribute 0 (`v_msad_u8`). - fn sad_lanes(&mut self, a: V, b: V, bits: u32, lanes: u32, masked: bool) -> V { - let c = self.cur; - let mask = self.s.m.i32((1u32 << bits) - 1); - let zero = self.s.m.i32(0); - let mut total = zero; - for lane in 0..lanes { - let (xa, xb) = if lane == 0 { - (a, b) - } else { - let sh = self.s.m.i32(lane * bits); - ( - self.s.m.bin(c, Bin::LShr, a, sh), - self.s.m.bin(c, Bin::LShr, b, sh), - ) - }; - let xa = self.s.m.bin(c, Bin::And, xa, mask); - let xb = self.s.m.bin(c, Bin::And, xb, mask); - let mut diff = self.abs_diff_u32(xa, xb); - if masked { - let is_zero = self.s.m.cmp(c, pred::EQ, xa, zero); - diff = self.s.m.select(c, is_zero, zero, diff); - } - total = if lane == 0 { - diff - } else { - self.s.m.bin(c, Bin::Add, total, diff) - }; - } - total - } - /// A 64-bit source (a register pair; inline constants sign-extend). fn src64(&mut self, inst: &Inst, k: usize) -> Result { let Fields::Valu(v) = &inst.fields else { @@ -8660,16 +7506,6 @@ impl<'a> Lower<'a> { } } - fn join64(&mut self, lo: V, hi: V) -> V { - let c = self.cur; - let ty = self.s.m.int(64); - let lo = self.s.m.cast(c, Cast::ZExt, lo, ty); - let hi = self.s.m.cast(c, Cast::ZExt, hi, ty); - let shift = self.s.m.int_const(ty, 32); - let hi = self.s.m.bin(c, Bin::Shl, hi, shift); - self.s.m.bin(c, Bin::Or, lo, hi) - } - /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying /// `abs` and `neg` input modifiers on operand `k`. fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> { @@ -8823,6 +7659,16 @@ impl<'a> Lower<'a> { self.s.m.select(c, is_under, under_res, r) } + fn join64(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let ty = self.s.m.int(64); + let lo = self.s.m.cast(c, Cast::ZExt, lo, ty); + let hi = self.s.m.cast(c, Cast::ZExt, hi, ty); + let shift = self.s.m.int_const(ty, 32); + let hi = self.s.m.bin(c, Bin::Shl, hi, shift); + self.s.m.bin(c, Bin::Or, lo, hi) + } + /// The bits of the float nearest the double whose dwords are `lo` and /// `hi`, on 32-bit integers: round to nearest even, infinities and NaN /// kept (a NaN stays quiet), a result below the smallest normal float @@ -8901,22 +7747,11 @@ impl<'a> Lower<'a> { /// op_sel (or an SDWA word select) picks the high half; inline float /// constants are f16 values here. fn half_src(&mut self, inst: &Inst, k: usize) -> Result { - self.half_src_with(inst, k, true) - } - - /// [`Self::half_src`] for a 16-bit compare: RDNA2 ignores VOP3 `op_sel` - /// on `v_cmp_*`/`v_cmpx_*` over f16, u16 and i16, and reads the low half; - /// an SDWA word select still picks the half it names. - fn half_cmp_src(&mut self, inst: &Inst, k: usize) -> Result { - self.half_src_with(inst, k, false) - } - - fn half_src_with(&mut self, inst: &Inst, k: usize, opsel: bool) -> Result { let Fields::Valu(v) = &inst.fields else { unreachable!() }; let op = *v.src.get(k).ok_or("a missing operand")?; - let mut high = opsel && v.opsel >> k & 1 != 0; + let mut high = v.opsel >> k & 1 != 0; if let Some(sd) = v.sdwa { match sd.src_sel.get(k).copied().unwrap_or(6) { 4 => {} @@ -8942,19 +7777,10 @@ impl<'a> Lower<'a> { /// An f16 source as an f32 (exact), with its abs/neg modifiers. fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result { - self.half_fsrc_with(inst, k, true) - } - - /// [`Self::half_fsrc`] for a 16-bit compare, which ignores `op_sel`. - fn half_cmp_fsrc(&mut self, inst: &Inst, k: usize) -> Result { - self.half_fsrc_with(inst, k, false) - } - - fn half_fsrc_with(&mut self, inst: &Inst, k: usize, opsel: bool) -> Result { let Fields::Valu(v) = &inst.fields else { unreachable!() }; - let h = self.half_src_with(inst, k, opsel)?; + let h = self.half_src(inst, k)?; let f32t = self.s.t.f32; let mut f = self .s @@ -8993,10 +7819,9 @@ impl<'a> Lower<'a> { } } let c = self.cur; - let old = if keep { - self.old_i32_of(inst.read(Reg::V(reg)), false, None) - } else { - self.s.m.i32(0) + let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { + Some(Ok(o)) if keep => o, + _ => self.s.m.i32(0), }; let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF)); let x = self.s.m.bin(c, Bin::And, x, low); @@ -9033,7 +7858,6 @@ impl<'a> Lower<'a> { "v_max3_f16", "v_min3_f16", "v_med3_f16", - "v_div_fixup_f16", ]; const FLOAT1: &[&str] = &[ "v_rcp_f16", @@ -9048,7 +7872,6 @@ impl<'a> Lower<'a> { "v_rndne_f16", "v_sin_f16", "v_cos_f16", - "v_frexp_mant_f16", "v_cvt_f16_u16", "v_cvt_f16_i16", ]; @@ -9057,8 +7880,6 @@ impl<'a> Lower<'a> { "v_sub_nc_u16", "v_subrev_nc_u16", "v_mul_lo_u16", - "v_mad_u16", - "v_mad_i16", "v_lshlrev_b16", "v_lshrrev_b16", "v_ashrrev_i16", @@ -9070,11 +7891,10 @@ impl<'a> Lower<'a> { "v_cvt_i16_f16", "v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16", - "v_frexp_exp_i16_f16", ]; let all = [FLOAT1, FLOAT2, FLOAT3, INT]; if !all.iter().any(|l| l.contains(&name)) - && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16" | "v_ldexp_f16") + && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16") { return None; } @@ -9128,49 +7948,6 @@ impl<'a> Lower<'a> { let f = self.fsrc(inst, 0)?; return float_result(self, f); } - if name == "v_ldexp_f16" { - // D.f16 = S0.f16 * 2^(S1.i16). S1 is a signed 16-bit integer exponent, - // so float abs/neg modifiers apply only to S0. - if (v.abs | v.neg) & 2 != 0 { - return Err("float modifier on v_ldexp_f16 exponent"); - } - let a = self.half_fsrc(inst, 0)?; - let raw_e = self.half_src(inst, 1)?; - let k16 = self.s.m.i32(16); - let e = self.s.m.bin(c, Bin::Shl, raw_e, k16); - let e = self.s.m.bin(c, Bin::AShr, e, k16); - // Clamp exponent to [-64, 64] so 2^e is always a normal finite f32: - // - +-0 * finite = +-0 (never 0 * inf = NaN), - // - +-inf * finite = +-inf (never inf * 0 = NaN), - // - min f16 (2^-24) * 2^64 overflows f16 to +-inf, - // - max f16 (~2^16) * 2^-64 underflows f16 to +-0. - let lo = self.s.m.i32((-64i32) as u32); - let hi = self.s.m.i32(64); - let under = self.s.m.cmp(c, pred::SLT, e, lo); - let e = self.s.m.select(c, under, lo, e); - let over = self.s.m.cmp(c, pred::SGT, e, hi); - let e = self.s.m.select(c, over, hi, e); - let bias = self.s.m.i32(127); - let k23 = self.s.m.i32(23); - let biased = self.s.m.bin(c, Bin::Add, e, bias); - let scale_bits = self.s.m.bin(c, Bin::Shl, biased, k23); - let scale = self.as_float(scale_bits); - let r = self.s.m.bin(c, Bin::Mul, a, scale); - // DXIL `legacyF32ToF16` rounds toward zero on NVIDIA/WARP and clamps finite - // values >= 65536 to 0x7BFF (max finite f16). Under RDNA2's default RTE mode, - // |r| >= 65520.0 (the f16 overflow threshold) overflows to signed infinity. - let abs_r = self.unary(6, r); - let ov_thresh = self.s.m.f32(65520.0f32.to_bits()); - let overflows = self.s.m.cmp(c, pred::OGE, abs_r, ov_thresh); - let r_bits = self.as_int(r); - let sign_mask = self.s.m.i32(0x8000_0000); - let inf_bits = self.s.m.i32(0x7F80_0000); - let r_sign = self.s.m.bin(c, Bin::And, r_bits, sign_mask); - let signed_inf_bits = self.s.m.bin(c, Bin::Or, r_sign, inf_bits); - let signed_inf = self.as_float(signed_inf_bits); - let r = self.s.m.select(c, overflows, signed_inf, r); - return float_result(self, r); - } if float2.contains(&name) { let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?); let r = match name { @@ -9216,7 +7993,6 @@ impl<'a> Lower<'a> { let t = self.max_min(false, a, b); self.max_min(false, t, acc) } - "v_div_fixup_f16" => self.div_fixup(a, b, acc), _ => self.med3(a, b, acc), }; return float_result(self, r); @@ -9240,10 +8016,6 @@ impl<'a> Lower<'a> { let one = self.s.m.f32(1.0f32.to_bits()); self.s.m.bin(c, Bin::SDiv, one, a) } - "v_frexp_mant_f16" => { - let a = self.half_fsrc(inst, 0)?; - self.frexp_f32(a).0 - } _ => { let a = self.half_fsrc(inst, 0)?; let op = match name { @@ -9300,20 +8072,8 @@ impl<'a> Lower<'a> { let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?; return self.write_half(inst, r, guard); } - if name == "v_frexp_exp_i16_f16" { - if v.clamp || v.omod != 0 { - return Err("modifiers on a 16-bit integer operation"); - } - let a = self.half_fsrc(inst, 0)?; - let (_, exp) = self.frexp_f32(a); - return self.write_half(inst, exp, guard); - } // 16-bit integers: computed on the low halves, the low 16 bits kept. - let saturates = matches!( - name, - "v_add_nc_u16" | "v_sub_nc_u16" | "v_subrev_nc_u16" | "v_mad_u16" | "v_mad_i16" - ); - if (v.clamp && !saturates) || v.omod != 0 || v.abs != 0 || v.neg != 0 { + if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 { return Err("modifiers on a 16-bit integer operation"); } let r = { @@ -9328,19 +8088,11 @@ impl<'a> Lower<'a> { b = sext(self, b); } let k15 = self.s.m.i32(15); - let r = match name { + match name { "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b), "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b), "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a), "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b), - "v_mad_u16" | "v_mad_i16" => { - let mut d = self.half_src(inst, 2)?; - if name == "v_mad_i16" { - d = sext(self, d); - } - let m = self.s.m.bin(c, Bin::Mul, a, b); - self.s.m.bin(c, Bin::Add, m, d) - } "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => { // src0 is the shift (4 bits), src1 the value. let sh = self.s.m.bin(c, Bin::And, a, k15); @@ -9366,30 +8118,6 @@ impl<'a> Lower<'a> { let t = self.s.m.cmp(c, p, a, b); self.s.m.select(c, t, a, b) } - }; - if v.clamp && saturates { - match name { - "v_add_nc_u16" | "v_mad_u16" => { - let hi = self.s.m.i32(0xFFFF); - let over = self.s.m.cmp(c, pred::IUGT, r, hi); - self.s.m.select(c, over, hi, r) - } - "v_sub_nc_u16" | "v_subrev_nc_u16" => { - let z = self.s.m.i32(0); - let under = self.s.m.cmp(c, pred::SLT, r, z); - self.s.m.select(c, under, z, r) - } - _ => { - let lo = self.s.m.i32(i32::from(i16::MIN) as u32); - let hi = self.s.m.i32(i32::from(i16::MAX) as u32); - let under = self.s.m.cmp(c, pred::SLT, r, lo); - let t = self.s.m.select(c, under, lo, r); - let over = self.s.m.cmp(c, pred::SGT, t, hi); - self.s.m.select(c, over, hi, t) - } - } - } else { - r } }; self.write_half(inst, r, guard) @@ -9493,89 +8221,6 @@ impl<'a> Lower<'a> { Ok(self.s.m.bin(c, Bin::And, x, m)) } - /// `v_pk_fmac_f16` (VOP2 `0x3c` / VOP3 `0x13c`): two packed f16 - /// multiply-accumulates (`d.lo = s0.lo * s1.lo + d.lo`, same for `hi`). - /// VOP3 `abs`/`neg`/`omod`/`clamp` apply to both halves. - fn pk_fmac_f16(&mut self, inst: &Inst, guard: Option) -> Result<(), Why> { - let Fields::Valu(v) = &inst.fields else { - unreachable!() - }; - if v.sdwa.is_some() { - return Err("SDWA on v_pk_fmac_f16"); - } - let Some(Operand::Vector { reg, .. }) = v.dst else { - return Err("a packed result outside a VGPR"); - }; - let c = self.cur; - let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); - let old = match inst.read(Reg::V(reg)) { - Some(o) => self.i32_of(o)?, - None => self.s.m.i32(0), - }; - let s0_raw = match self.src0 { - Some(x) => x, - None => { - let op = *v.src.first().ok_or("a missing operand")?; - self.f16_operand(inst, &op)? - } - }; - let op1 = *v.src.get(1).ok_or("a missing operand")?; - let s1_raw = self.f16_operand(inst, &op1)?; - - let k16 = self.s.m.i32(16); - let m16 = self.s.m.i32(0xFFFF); - let mut halves = Vec::with_capacity(2); - for high in [false, true] { - let mut lane_f = |raw: V, k: usize| { - let h = if high { - self.s.m.bin(c, Bin::LShr, raw, k16) - } else { - raw - }; - let h = self.s.m.bin(c, Bin::And, h, m16); - let mut f = self - .s - .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); - if v.abs >> k & 1 != 0 { - f = self.unary(6, f); - } - if v.neg >> k & 1 != 0 { - let z = self.s.m.f32(0x8000_0000); - f = self.s.m.bin(c, Bin::Sub, z, f); - } - f - }; - let a = lane_f(s0_raw, 0); - let b = lane_f(s1_raw, 1); - let acc_h = if high { - self.s.m.bin(c, Bin::LShr, old, k16) - } else { - old - }; - let acc_h = self.s.m.bin(c, Bin::And, acc_h, m16); - let acc = self - .s - .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[acc_h]); - let mut f = self.fmad(a, b, acc); - if v.omod != 0 { - let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(v.omod)]; - let kf = self.s.m.f32(factor.to_bits()); - f = self.s.m.bin(c, Bin::Mul, f, kf); - } - if v.clamp { - f = self.unary(7, f); - } - let h = self - .s - .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); - halves.push(self.s.m.bin(c, Bin::And, h, m16)); - } - let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16); - let r = self.s.m.bin(c, Bin::Or, halves[0], hi); - self.write(inst, Reg::V(reg), r, guard); - Ok(()) - } - /// Packed 16-bit operations (`v_pk_*`): each half computed as the /// 16-bit operation does, f16 through f32 as in [`Self::valu16`]. fn packed16(&mut self, inst: &Inst, op: &str, guard: Option) -> Result<(), Why> { @@ -9590,11 +8235,7 @@ impl<'a> Lower<'a> { | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2, _ => return Err("a packed 16-bit operation"), }; - let saturates = matches!( - op, - "add_u16" | "sub_u16" | "mad_u16" | "add_i16" | "sub_i16" | "mad_i16" - ); - if v.omod != 0 || !float && ((v.clamp && !saturates) || v.neg != 0 || v.neg_hi != 0) { + if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) { return Err("modifiers on a packed integer operation"); } let c = self.cur; @@ -9644,7 +8285,7 @@ impl<'a> Lower<'a> { } } let k15 = self.s.m.i32(15); - let r = match op { + match op { "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]), "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]), "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]), @@ -9676,34 +8317,6 @@ impl<'a> Lower<'a> { let t = self.s.m.cmp(c, p, xs[0], xs[1]); self.s.m.select(c, t, xs[0], xs[1]) } - }; - if v.clamp && saturates { - match op { - // Unsigned: add/mad fit in u32 (max 65535*65535+65535 <= u32::MAX); - // sub is in [-65535, 65535] so signed < 0 catches underflow. - "add_u16" | "mad_u16" => { - let hi = self.s.m.i32(0xFFFF); - let over = self.s.m.cmp(c, pred::IUGT, r, hi); - self.s.m.select(c, over, hi, r) - } - "sub_u16" => { - let z = self.s.m.i32(0); - let under = self.s.m.cmp(c, pred::SLT, r, z); - self.s.m.select(c, under, z, r) - } - // Signed: operands are sign-extended i16 in i32, so add/sub/mad - // never wrap i32 (|r| <= 32768*32768 + 32768 < 2^31). - _ => { - let lo = self.s.m.i32(i32::from(i16::MIN) as u32); - let hi = self.s.m.i32(i32::from(i16::MAX) as u32); - let under = self.s.m.cmp(c, pred::SLT, r, lo); - let t = self.s.m.select(c, under, lo, r); - let over = self.s.m.cmp(c, pred::SGT, t, hi); - self.s.m.select(c, over, hi, t) - } - } - } else { - r } }; let m = self.s.m.i32(0xFFFF); @@ -10065,7 +8678,7 @@ impl<'a> Lower<'a> { return Err("v_mbcnt of a mask that is no ballot (console lane layout)"); } self.s.flags |= flags::WAVE_OPS; - } else if !self.is_mesh() { + } else if self.s.mesh.is_none() { self.cross_lane(false)?; } let lane = self.console_lane(); @@ -10168,7 +8781,7 @@ impl<'a> Lower<'a> { } "f32" | "f16" => { let (a, b) = if ty == "f16" { - (self.half_cmp_fsrc(inst, 0)?, self.half_cmp_fsrc(inst, 1)?) + (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?) } else { (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?) }; @@ -10203,10 +8816,6 @@ impl<'a> Lower<'a> { } } "u64" | "i64" => { - if matches!(op, "f" | "t") { - self.lane(inst, Some(op == "t")); - return Ok(()); - } let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?); let signed = ty == "i64"; let p = match op { @@ -10226,7 +8835,7 @@ impl<'a> Lower<'a> { } "u32" | "i32" | "u16" | "i16" => { let (a, b) = if ty.ends_with("16") { - let (mut a, mut b) = (self.half_cmp_src(inst, 0)?, self.half_cmp_src(inst, 1)?); + let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); if ty == "i16" { let k16 = self.s.m.i32(16); for x in [&mut a, &mut b] { @@ -10575,11 +9184,10 @@ impl<'a> Lower<'a> { /// results keep the register's high half (GFX10). fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V { let c = self.cur; - let old = self.old_i32_of( - inst.read(Reg::V(reg)), - false, - Some("the first half of an interpolation"), - ); + let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { + Some(Ok(o)) => o, + _ => self.s.m.i32(0), + }; let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF)); let old = self.s.m.bin(c, Bin::And, old, high); let x = self.s.m.bin(c, Bin::And, x, low); @@ -10677,8 +9285,6 @@ impl<'a> Lower<'a> { "umax" => 7, "swap" => 8, "cmpswap" => u32::MAX, - // No DXIL operation: a compare-and-swap loop (`atomic_loop`). - "inc" | "dec" | "fcmpswap" | "fmin" | "fmax" => ATOMIC_LOOP, _ => return Err(name), }; let Fields::Image { cache, .. } = &inst.fields else { @@ -10689,9 +9295,7 @@ impl<'a> Lower<'a> { } // Compare-exchange consumes a replacement followed by a comparand. let compare = code == u32::MAX; - // fcmpswap's loop compares against a second data dword. - let pair = compare || (code == ATOMIC_LOOP && op == "fcmpswap"); - let wide = match (pair, *dmask) { + let wide = match (compare, *dmask) { (false, 1) | (true, 3) => false, (false, 3) | (true, 15) => true, _ => return Err("an image atomic data mask"), @@ -10705,11 +9309,9 @@ impl<'a> Lower<'a> { return Err("image atomic data"); }; let width = if wide { 2 } else { 1 }; - let vals = self.vgprs(inst, data, if pair { 2 * width } else { width })?; + let vals = self.vgprs(inst, data, if compare { 2 * width } else { width })?; let (ty, component) = if wide { - self.s.flags |= flags::INT64 - | flags::ATOMIC_INT64_ON_TYPED_RESOURCE - | flags::ATOMIC_INT64_ON_HEAP_RESOURCE; + self.s.flags |= flags::INT64 | flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64; (self.s.m.int(64), 0x107) // one uint64_t in an R32G32_UINT view } else { (self.s.t.i32, 0x105) @@ -10726,20 +9328,6 @@ impl<'a> Lower<'a> { original }; let h = self.handle(site, src, false, (kind | 0x1000, component))?; - if code == ATOMIC_LOOP { - // No DXIL operation: emulate with a compare-and-swap loop. - let old = match inst.read(Reg::V(reg)) { - Some(v) if cache.glc => self.i32_of(v)?, - _ => self.s.m.i32(0), - }; - let at = self.begin_guarded(guard); - let r = self.atomic_loop(h, &cs, op, &vals); - let r = self.end_guarded(at, &[(r, old)])[0]; - if cache.glc { - self.write(inst, Reg::V(reg), r, None); - } - return Ok(()); - } let mut args = vec![h]; let (intrinsic, opcode) = if compare { let comparand = if wide { @@ -10845,13 +9433,12 @@ impl<'a> Lower<'a> { "image_sample_lz" | "image_sample_l" | "image_sample_lz_o" => (62, true), "image_sample_b" | "image_sample_b_cl" => (61, true), "image_sample_c_lz" => (65, true), - "image_sample_d" | "image_sample_d_g16" | "image_sample_d_cl" => (63, true), + "image_sample_d" | "image_sample_d_cl" => (63, true), "image_get_lod" if self.s.pixel => (81, true), // Implicit derivatives: pixel shaders only. "image_sample_c" if self.s.pixel => (64, true), "image_sample_c_cl" if self.s.pixel => (64, true), - "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" - | "image_gather4_l_o" => (73, true), + "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" | "image_gather4_l_o" => (73, true), "image_load" | "image_load_mip" => (66, false), "image_get_resinfo" => (72, false), _ => return Err(name), @@ -10864,7 +9451,7 @@ impl<'a> Lower<'a> { let mip = if uav { self.s.m.undef(self.s.t.i32) } else { - addr_u32(self, 0)? + addr_val(self, 0)? }; let i32t = self.s.t.i32; let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); @@ -10911,20 +9498,23 @@ impl<'a> Lower<'a> { return Err("a comparison sample of 16-bit coordinates or several channels"); } let sh = self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?; - // Texel offsets (`_o`) come first as a whole dword: x in bits 0-5, - // y in 8-13, signed (programmable offsets: gathers only). + // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13, + // signed (programmable offsets: gathers only). let offset_word = name.ends_with("_o"); let first = usize::from(offset_word) + usize::from(name.starts_with("image_sample_b")) + usize::from(cmp); // Coordinates the size divides (not the array slice); explicit - // gradients (x then y) come before the coordinates, packed only - // when `_g16` is set (independently of `a16`). + // gradients (x then y) come before the coordinates. let spatial = coords - usize::from(kind == 6 || kind == 7); // A cube's gradients are the two of its face coordinates. let grads = if kind == 5 { 2 } else { spatial }; let deriv_regs = if op == 63 { - if *a16 { grads.div_ceil(2) } else { grads } + if *a16 { + grads.div_ceil(2) + } else { + grads + } } else { 0 }; @@ -11201,16 +9791,6 @@ impl<'a> Lower<'a> { if dmask.count_ones() != 1 { return Err("a gather of several channels"); } - if offset_word { - let w = addr_u32(self, 0)?; - for (k, at) in [(0, 26), (1, 18)] { - // Bits at..at+5 sign-extended: shift up, then down. - let left = self.s.m.i32(at); - let t = self.s.m.bin(c, Bin::Shl, w, left); - let k26 = self.s.m.i32(26); - os[k] = self.s.m.bin(c, Bin::AShr, t, k26); - } - } if matches!(name, "image_gather4_l" | "image_gather4_l_o") && coords == 2 && spatial == 2 @@ -11222,8 +9802,8 @@ impl<'a> Lower<'a> { // are read at the level instead, in the gather's // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0). // With an offset too (`image_gather4_l_o`): the - // offset is in texels of that level. Grand Theft - // Auto VI's meshlet culling takes a 4x4 block of + // offset is in texels of that level. + // The title's meshlet culling takes a 4x4 block of // the pyramid as one gather and three offset ones // ((2,0), (0,2), (2,2)); the three read level 0, // two texels beside the first one's place, so a @@ -11266,12 +9846,7 @@ impl<'a> Lower<'a> { let ch = dmask.trailing_zeros(); let mut g = [fu; 4]; let mut read = None; - let texels = [ - (lo[0], hi[1]), - (hi[0], hi[1]), - (hi[0], lo[1]), - (lo[0], lo[1]), - ]; + let texels = [(lo[0], hi[1]), (hi[0], hi[1]), (hi[0], lo[1]), (lo[0], lo[1])]; for (slot, (x, y)) in g.iter_mut().zip(texels) { let r = self.s.op( c, @@ -11905,7 +10480,7 @@ impl<'a> Lower<'a> { return Err("a compressed export"); } let guard = self.guard(b, i)?; - let mesh = self.is_mesh(); + let mesh = self.s.mesh.is_some(); let c = self.cur; if let Some(g) = guard && !mesh @@ -11919,9 +10494,6 @@ impl<'a> Lower<'a> { .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]); } if mesh && e.target == Target::Primitive { - if self.mesh_emu.is_some() { - return self.emit_indices_emu(e, guard); - } return self.emit_indices(e, guard); } let param_row = |usage: Usage, row: u8| match usage { @@ -11934,11 +10506,10 @@ impl<'a> Lower<'a> { // outputs are elements of `prims`. let mut stores = Vec::new(); let primitive = matches!(e.target, Target::PrimitiveParam { .. }); - let outputs = match (&self.mesh_emu, primitive) { - (Some(m), true) => &m.prim_sigs, - (Some(m), false) => &m.vertex_sigs, - (None, true) => &self.s.prims, - (None, false) => &self.s.outputs, + let outputs = if primitive { + &self.s.prims + } else { + &self.s.outputs }; let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind); // 16-bit vertex outputs: the halves each dword carries, as (output @@ -12041,13 +10612,7 @@ impl<'a> Lower<'a> { } } fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec { - if let Some(m) = l.mesh_emu.as_mut() { - if primitive { - &mut m.prim_sigs - } else { - &mut m.vertex_sigs - } - } else if primitive { + if primitive { &mut l.s.prims } else { &mut l.s.outputs @@ -12059,9 +10624,6 @@ impl<'a> Lower<'a> { { return Err("a 16-bit output the stage data does not mark"); } - if self.mesh_emu.is_some() { - return self.store_mesh_emu_outputs(guard, primitive, &stores); - } // A mesh lane writes its own vertex or primitive, where it exports. let at = if mesh { let flat = self.mesh_thread(); @@ -12211,11 +10773,9 @@ impl<'a> Lower<'a> { .iter() .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r) }; - let vertex_sigs = match &self.mesh_emu { - Some(m) => &m.vertex_sigs, - None => &self.s.outputs, - }; - let free: std::collections::BTreeSet = vertex_sigs + let free: std::collections::BTreeSet = self + .s + .outputs .iter() .filter(|o| o.kind == 0) .filter_map(|o| o.row) @@ -12226,6 +10786,318 @@ impl<'a> Lower<'a> { _ => None, } } + + fn exit(&mut self, b: usize) -> Result<(), Stop> { + let offset = self.x.p.blocks[b] + .insts + .last() + .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset); + let term = match self.x.st.exits[b] { + LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => { + let ok = self.count_iteration(t, pred::IULT); + let abort = self.abort_block(); + Term::CondBr(ok, self.block[t].expect("reachable"), abort) + } + LaneExit::Jump(t) => { + self.enter_loop(b, t, self.cur); + Term::Br(self.block[t].expect("reachable")) + } + LaneExit::Branch { + when, + taken, + not_taken, + } => { + // A negated condition branches the other way round. + let (cond, taken, not_taken) = match self.x.st.bools.node(when) { + _ if self.x.st.wide.contains(&b) => { + let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?; + (c, taken, not_taken) + } + Some((atom, Bool::TRUE, Bool::FALSE)) => { + let a = self + .atom(atom, self.cur) + .map_err(|w| unsupported(offset, w))?; + (a, not_taken, taken) + } + _ => { + let c = self + .boolean(when, self.cur) + .map_err(|w| unsupported(offset, w))?; + (c, taken, not_taken) + } + }; + // A back edge is taken only below the iteration limit. + let back = + |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b]; + // (No `xor` of a compare: a loop exit testing one hung the + // AMD driver.) + let cond = if back(self, taken) { + let ok = self.count_iteration(taken, pred::IULT); + self.s.m.bin(self.cur, Bin::And, cond, ok) + } else if back(self, not_taken) { + let stop = self.count_iteration(not_taken, pred::IUGE); + self.s.m.bin(self.cur, Bin::Or, cond, stop) + } else { + cond + }; + // Critical edges get a block of their own, so loops have + // dedicated exits and preheaders as DXC emits them. + let (t, f) = (self.edge(b, taken), self.edge(b, not_taken)); + for (to, via) in [(taken, t), (not_taken, f)] { + if !back(self, to) { + // From an edge block, or from here. + let from = if Some(via) == self.block[to] { + self.cur + } else { + via + }; + self.enter_loop(b, to, from); + } + } + Term::CondBr(cond, t, f) + } + LaneExit::End => { + if self.s.pixel && !self.exported[b] && !self.has_done_export(b) { + // A lane leaving without its final export was killed. + let t = self.s.m.bool(true); + self.s + .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); + } + Term::Ret + } + LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")), + }; + let _ = Exit::End; + self.s.m.terminate(self.cur, term); + Ok(()) + } + + /// A forward edge into loop header `to` (from DXIL block `via`) starts + /// its count at 0. + fn enter_loop(&mut self, _from: usize, to: usize, via: usize) { + if let Some((_, incoming)) = self.counters.get_mut(&to) { + let z = self.s.m.i32(0); + incoming.push((z, via)); + } + } + + /// A back edge to header `to` (a back edge keeps its block, no + /// critical-edge block): the count goes up; the result compares it with + /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop). + fn count_iteration(&mut self, to: usize, p: u8) -> V { + let c = self.cur; + let (phi, _) = self.counters[&to]; + let one = self.s.m.i32(1); + let next = self.s.m.bin(c, Bin::Add, phi, one); + self.s.m.tag(phi, Tag::Counter); + self.s.m.tag(next, Tag::Counter); + // Per stage unless the switch names one: a loop that never meets its + // exit (a count read from a buffer the host has not got yet, say) + // runs to the limit in every lane. A million iterations a pixel + // hung the GPU for seconds a draw until Windows reset it + // (PS_Textured_Eight, 2026-11-24, run 12). + // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop + // past 256 or a compute loop past 4,096 is cut short. (They were + // 1,024, 4,096 and 65,536: the opening cutscene then lost the card + // 14-25 frames in, in a minimap or shadow mesh draw; with every + // loop cut at 64 it ran 90 frames. Raise them again once shaders + // stop reading data that is not there yet.) + let limit = match super::loop_limit() { + LOOP_LIMIT if self.s.pixel => 1 << 7, + LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8, + LOOP_LIMIT => 1 << 12, + named => named, + }; + let limit = self.s.m.i32(limit); + self.counters + .get_mut(&to) + .expect("header") + .1 + .push((next, c)); + let over = self.s.m.cmp(c, p, next, limit); + self.s.m.tag(over, Tag::Counter); + over + } + + /// The block a lane stopped by [`LOOP_LIMIT`] leaves through. + fn abort_block(&mut self) -> usize { + if let Some(a) = self.abort { + return a; + } + let a = self.s.m.new_block(); + if self.s.pixel { + let t = self.s.m.bool(true); + self.s + .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); + } + self.s.m.terminate(a, Term::Ret); + self.abort = Some(a); + a + } + + /// The DXIL block a branch from IR block `from` to `to` goes to. + fn edge(&mut self, from: usize, to: usize) -> usize { + let target = self.block[to].expect("reachable"); + let preds = self.x.p.blocks[to] + .preds + .iter() + .filter(|&&q| self.block[q].is_some()) + .count(); + // Back edges stay as they are: the exiting block is the latch. + if preds < 2 || self.rpo[to] <= self.rpo[from] { + return target; + } + let e = self.s.m.new_block(); + self.s.m.terminate(e, Term::Br(target)); + self.edges.insert((from, to), e); + e + } + + fn fill_phis(&mut self) -> Result<(), Stop> { + let p = self.x.p; + // Lane-mask joins first (what an edge brings may ask for more joins, + // of masks and of numbers): each edge's mask as the structure + // tracked it, a constant or a scalar-built one included. + let st = self.x.st; + while let Some((v, b, i)) = self.pending_masks.pop() { + let phi = &p.blocks[b].phis[i]; + let offset = p.blocks[b].offset; + let args = st + .phi_masks + .get(&phi.value) + .ok_or_else(|| unsupported(offset, "a lane-mask join of an untracked mask"))?; + let mut incoming = Vec::new(); + for (n, &q) in p.blocks[b].preds.iter().enumerate() { + let Some(qb) = self.tail[q] else { continue }; + let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); + let x = self.boolean(args[n], qb).map_err(|w| unsupported(offset, w))?; + incoming.push((x, qb)); + } + self.s.m.set_phi(v, incoming); + } + // A join that only another join reads is read wherever that one is. Left + // unmarked, a value without a DXIL form coming into it became zero without a + // word (the looked-up tint of the material resolve programs, whose size + // computation had no value, was zero in every lane that way). + // shortcut: only with `VICTORY_STRICT_JOINS` set (the offline pack + // listing sets it to count them): 40 programs that translate today + // stop by name with it (vehicle paint pixel shaders at "the first + // half of an interpolation", foliage mesh shaders); until those are + // lowered they keep drawing with that zero. + static STRICT: std::sync::OnceLock = std::sync::OnceLock::new(); + let strict = *STRICT.get_or_init(|| std::env::var_os("VICTORY_STRICT_JOINS").is_some()); + let mut work: Vec = if strict { + self.read_phis.iter().copied().collect() + } else { + Vec::new() + }; + while let Some(v) = work.pop() { + let Some(&(b, i)) = self.phi_at.get(&v) else { + continue; + }; + for &a in &p.blocks[b].phis[i].args { + if self.phi_at.contains_key(&a) && self.read_phis.insert(a) { + work.push(a); + } + } + } + for (v, b, i) in std::mem::take(&mut self.data_phis) { + let phi = &p.blocks[b].phis[i]; + let bit = phi.reg == Reg::Scc; + // A join of numbers with dead registers (`dead`): the paths that bring those + // never read the result, so they bring zero. Not for a join that is itself a + // lane mask (a ballot gives that one as data). + let st = self.x.st; + let numbers = !bit + && !st.masks.contains_key(&phi.value) + && !st.highs.contains_key(&phi.value) + && phi + .args + .iter() + .any(|a| matches!(self.vals.get(a), Some(Val::I32(_)))); + let mut incoming = Vec::new(); + 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 arg = phi.args[n]; + if self.read_phis.contains(&phi.value) && !self.vals.contains_key(&arg) { + let _ = self.lazy_barycentric(arg); + // A root parameter nothing read before the join (user + // data is loaded on first use, in the entry block). + if !self.vals.contains_key(&arg) + && let Some(&(param, dword)) = self.params.get(&arg) + { + let val = self.user(param, dword); + self.vals.insert(arg, val); + } + } + let x = match (self.vals.get(&arg).copied(), bit) { + (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x, + (Some(Val::Missing(_)) | None, false) + if numbers && self.dead(arg, &mut Vec::new()) => + { + self.s.m.i32(0) + } + // A lane mask joined with numbers (a traversal that keeps its lanes' masks on + // a stack with its node numbers): the mask comes as the number it is, the + // ballot of its lanes where it is written. + (Some(Val::Missing(_)) | None, false) + if self.read_phis.contains(&phi.value) + && self.mask_data == MaskData::Console + && (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) => + { + match self.mask_dword(arg) { + Ok(x) => x, + Err(why) => return Err(Stop::Retry(phi.value, why)), + } + } + // SCC of a mask operation ("some lane is left") joined with a scalar test: + // the compiler branches around code that sets SCC and tests SCC after it, + // the skip bringing "no lane" along. As data it is "some lane of the wave + // has the bit" - right only if the wave took that skip together, as the + // console does: a lane that skipped alone would bring "some lane" where the + // console has the skipped code's SCC. So the branch must be one the wave + // takes together; else its region is named for `emit`'s retry to widen it. + (Some(Val::Missing(_)) | None, true) + if self.read_phis.contains(&phi.value) + && self.mask_data == MaskData::Console + && st.scc_some.contains_key(&arg) => + { + let per_lane = !st.wide.contains(&q) + && matches!(st.exits[q], LaneExit::Branch { when, .. } + if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_)))); + if per_lane { + for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) { + need(other); + } + return Err(Stop::Retry(phi.value, LANE_MASK)); + } + match self.scc_some(arg) { + Ok(x) => x, + Err(why) => return Err(Stop::Retry(phi.value, why)), + } + } + (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); + } + (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, why)); + } + _ if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, "a join of mismatched values")); + } + _ if bit => self.s.m.bool(false), + _ => self.s.m.i32(0), + }; + incoming.push((x, qb)); + } + self.s.m.set_phi(v, incoming); + } + for (phi, incoming) in std::mem::take(&mut self.counters).into_values() { + self.s.m.set_phi(phi, incoming); + } + Ok(()) + } } /// The DXIL interpolation mode of a kind of barycentrics (none for the @@ -12242,7 +11114,608 @@ fn interp_mode(kind: Barycentric) -> Option { }) } -include!("lower/methods.rs"); -include!("lower/mesh_emu.rs"); #[cfg(test)] -mod tests; +mod tests { + use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; + use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, + }; + use crate::{io, ir, resource, structure}; + + const S_ENDPGM: u32 = 0xBF81_0000; + + #[test] + fn packed_pixel_inputs_find_their_second_row() { + use super::super::container::SigElement; + use super::half_input_partners; + use crate::native::{PsInput, Usage}; + let entry = |row, row2, pack2| PsInput { + usage: Usage::Generic, + row, + mask: 0xF, + attr: row, + flat: false, + fp16: true, + pack2, + row2, + }; + let element = |row| SigElement { + name: "TEXCOORD".into(), + index: row, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: true, + }; + // Rows 0 and 3 pack and leave their second row out; 5 names its + // own (6). Unnamed 16-bit rows: 1, 4, 6, 7. + let io = StageIo::Ps { + inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }; + let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into(); + let p = half_input_partners(&io, &sig); + assert_eq!(p.get(&0), Some(&1)); + assert_eq!(p.get(&3), Some(&4)); + assert_eq!(p.get(&5), None); + } + + /// The packed pedestrian layouts of the title: an element + /// behind another one in its register follows in the first parameter + /// with a dword left, and is not a half of its register's row. + #[test] + fn packed_elements_behind_another_take_the_first_free_dword() { + use super::super::container::SigElement; + use super::packed_half; + let element = |index, row, col, cols| SigElement { + name: "TEXCOORD".into(), + index, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col, + cols, + usage: 0, + half: true, + }; + // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel + // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4 + // column 3; parameter 3 (rows 6 and 7) carries it in dword 3. + let sig = vec![ + element(1, 2, 0, 4), + element(2, 3, 0, 4), + element(4, 4, 0, 3), + element(6, 4, 3, 1), + element(3, 5, 0, 4), + element(5, 6, 0, 4), + element(7, 7, 0, 2), + element(9, 9, 0, 3), + element(11, 10, 0, 3), + element(15, 12, 0, 4), + ]; + let packs = [ + (2, Some(3)), + (4, Some(5)), + (6, Some(7)), + (9, Some(10)), + (12, None), + ]; + let at = |a, h| packed_half(&sig, &packs, a, h); + // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3. + assert_eq!(at(4, 2), Some((4, 2))); + assert_eq!(at(4, 3), None); + assert_eq!(at(4, 4), Some((5, 0))); + assert_eq!(at(4, 7), Some((5, 3))); + // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone. + assert_eq!(at(6, 3), Some((6, 3))); + assert_eq!(at(6, 5), Some((7, 1))); + assert_eq!(at(6, 6), Some((4, 3))); + assert_eq!(at(6, 7), None); + // Parameters without such an element are as before. + assert_eq!(at(9, 3), None); + assert_eq!(at(9, 4), Some((10, 0))); + assert_eq!(at(12, 3), Some((12, 3))); + assert_eq!(at(12, 4), None); + // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at + // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1, + // TEXCOORD7. + let sig = vec![ + element(0, 1, 0, 2), + element(7, 1, 2, 2), + element(1, 2, 0, 4), + element(2, 3, 0, 4), + element(4, 4, 0, 3), + ]; + let packs = [(3, Some(4)), (1, Some(2))]; + let at = |a, h| packed_half(&sig, &packs, a, h); + assert_eq!(at(1, 1), Some((1, 1))); + assert_eq!(at(1, 2), Some((2, 0))); + assert_eq!(at(1, 5), Some((2, 3))); + assert_eq!(at(1, 6), Some((1, 2))); + assert_eq!(at(1, 7), Some((1, 3))); + assert_eq!(at(3, 6), Some((4, 2))); + assert_eq!(at(3, 7), None); + // A row no element holds gives nothing, as before. + assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None); + } + + /// Whether a synthetic compute program translates with these input registers. + fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .map(|_| ()) + } + + /// Lowers a compute program with the root parameters `layout` (in user + /// SGPRs from s0 on) and the used resources `used`. + fn lower_with( + words: &[u32], + layout: Vec, + used: Vec, + ) -> Result { + lower_wave(words, layout, used, false) + } + + /// [`lower_with`] in wave64 if `wave64`. + fn lower_wave( + words: &[u32], + layout: Vec, + used: Vec, + wave64: bool, + ) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 256, + layout, + used, + io: StageIo::Cs(ComputeIo { + // The layout's user SGPRs (at least two), 512 bytes of LDS. + rsrc2: 1 << 15 | sgprs.max(2) << 1, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, wave64, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + } + + /// Root parameter `slot` in user SGPRs from `user_data` on. + fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs: if root == RootType::Descriptor { 2 } else { 1 }, + base_register: 0, + user_data, + slot, + } + } + + #[test] + fn buffer_cache_invalidations_lower_as_no_ops() { + // MUBUF opcode 0x071/0x072 with no data operand: the title asks the + // host to invalidate its cached view of a buffer. + assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv"); + assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv"); + } + + #[test] + fn a_scalar_carry_chain_reaches_the_select() { + // The high dword of a 64-bit add or subtract, then a select on the + // carry (borrow) the high half leaves in SCC, and a branch on it + // (only code with an effect needs its operands). + let add = [ + 0xBE80_03C1, // s_mov_b32 s0, -1 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8000_8100, // s_add_u32 s0, s0, 1 + 0x8201_8001, // s_addc_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + let sub = [ + 0xBE80_0380, // s_mov_b32 s0, 0 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8080_8100, // s_sub_u32 s0, s0, 1 + 0x8281_8001, // s_subb_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + + for words in [add, sub] { + lowers(&words, 0).unwrap(); + } + } + + fn perm_features(selector: u32) -> u64 { + // Synthetic compute shader: + // v0 is the thread ID and can supply a dynamic selector. + // Store the result in LDS to keep the permutation live. + let words = [ + 0x7E02_02FFu32, + 0x817F_34AB, + 0x7E04_02FF, + 0xFE01_56CD, + 0xD744_0003, + 257 | (258 << 9) | (selector << 18), + 0x3408_0082, + 0xD834_0000, + 0x0000_0304, + S_ENDPGM, + ]; + + let code: Vec = words.iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15, + threads: [64, 1, 1], + }), + code, + }; + + let p = ir::build(&native.code, false, 256).unwrap(); + + assert!(p.blocks.iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32")); + + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + + let io = io::raise(&p, &native).unwrap(); + + let emitted = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }).unwrap(); + + let container = + crate::Container::parse(&emitted.dxil).unwrap(); + + let features = + container.part(crate::FourCC::SFI0).unwrap(); + + u64::from_le_bytes(features.data.try_into().unwrap()) + } + + #[test] + fn perm_constant_selector_needs_no_int64() { + assert_eq!(perm_features(128) & 0x8000, 0); + } + + #[test] + fn perm_dynamic_selector_needs_no_int64() { + assert_eq!( + perm_features(256) & 0x8000, + 0, + "dynamic v_perm_b32 must not require INT64" + ); + } + + #[test] + fn a_descriptor_selected_by_scc_picks_its_heap_index() { + // Two buffer descriptors loaded from the table at s0, one picked by + // a root constant (s1) with s_cselect_b64 per half, and loaded + // through by index and stored to LDS so the load is needed. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xF408_0302, + 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] + 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] + 0xE030_2000, + 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + // Both are structured buffers of dwords in the table's range. + let used = || { + vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }] + }; + lower_with(&words, layout(), used()).unwrap(); + } + + /// Tables of 2D textures at s0 and samplers at s1. + fn texture_tables() -> (Vec, Vec) { + let range = |kind, user_data, slot| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, + user_data, + slot, + }; + ( + vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], + vec![ + range(ResourceType::Srv, 0, 0), + range(ResourceType::Sampler, 1, 1), + ], + ) + } + + #[test] + fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { + use crate::resource::tests::{ + WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, + }; + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + (WATERFALL_PICKED_WAVE32, false), + ] { + let (layout, used) = texture_tables(); + let l = lower_wave(words, layout, used, wave64).unwrap(); + // The loop's reads of the first lane became each lane's own + // dwords: no wave operation is left. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } + } + + /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. + pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { + let (layout, mut used) = texture_tables(); + used.push(UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 16, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }); + (layout, used) + } + + #[test] + fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { + use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; + for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { + let (layout, used) = texture_and_uav_tables(); + let l = lower_wave(words, layout, used, false).unwrap(); + // One image handle, from the join's per-lane heap index. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } + } + + #[test] + fn scalar_bit_tests_lower() { + // Each tests one bit of a constant into SCC and branches on it (only + // code with an effect needs its operands). + let tail = [ + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let bit_tests: [&[u32]; 4] = [ + &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 + &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 + ], + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 + ], + ]; + for head in bit_tests { + let words: Vec = head.iter().chain(&tail).copied().collect(); + lowers(&words, 0).unwrap(); + } + } + + #[test] + #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"] + fn a_missing_value_stays_missing_through_two_live_joins() { + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // skip the first overwrite + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) + 0xBF85_0001, // skip the second overwrite + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // use the result to branch + 0xBE83_0380, + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + // Compare to a direct read so future timestamp support works in both cases. + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[8..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); + words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead + lowers(&words, group_ids_xy).expect("dead timestamp"); + } + + #[test] + fn buffer_formats_by_number() { + // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, + // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. + assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); + assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); + assert_eq!( + buffer_format(50), + Some((&[10, 10, 10, 2][..], Numeric::Unorm)) + ); + assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); + assert_eq!( + buffer_format(77), + Some((&[32, 32, 32, 32][..], Numeric::Float)) + ); + // Invalid, past the table. + assert_eq!(buffer_format(0), None); + assert_eq!(buffer_format(78), None); + } + + #[test] + fn packed_buffer_formats_by_number() { + // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, + // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT + // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. + assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); + assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); + assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); + assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); + assert_eq!( + buffer_format(44), + Some((&[2, 10, 10, 10][..], Numeric::Unorm)) + ); + assert_eq!( + buffer_format(45), + Some((&[2, 10, 10, 10][..], Numeric::Snorm)) + ); + assert_eq!( + buffer_format(46), + Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) + ); + assert_eq!( + buffer_format(47), + Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) + ); + assert_eq!( + buffer_format(48), + Some((&[2, 10, 10, 10][..], Numeric::Uint)) + ); + assert_eq!( + buffer_format(49), + Some((&[2, 10, 10, 10][..], Numeric::Sint)) + ); + } + + /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as + /// `legacyF16ToF32` widens it. + fn half(h: u32) -> f32 { + let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); + let v = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 if m == 0 => f32::INFINITY, + 31 => f32::NAN, + _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), + }; + if s == 1 { -v } else { v } + } + + #[test] + fn small_floats_widen_as_halves() { + // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a + // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. + let f11 = |x: u32| half(x << half_shift(11)); + let f10 = |x: u32| half(x << half_shift(10)); + assert_eq!(f11(0), 0.0); + assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal + assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal + assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal + assert_eq!(f11(0x3C0), 1.0); + assert_eq!(f11(0x3E0), 1.5); + assert_eq!(f11(0x7BF), 65024.0); // largest + assert_eq!(f11(0x7C0), f32::INFINITY); + assert!(f11(0x7C1).is_nan()); + assert_eq!(f10(0x001), 2f32.powi(-19)); + assert_eq!(f10(0x020), 2f32.powi(-14)); + assert_eq!(f10(0x1E0), 1.0); + assert_eq!(f10(0x3DF), 64512.0); + assert_eq!(f10(0x3E0), f32::INFINITY); + assert!(f10(0x3FF).is_nan()); + // A 16-bit float is a half already, sign included. + assert_eq!(half(0xBC00 << half_shift(16)), -1.0); + } +} diff --git a/crates/victory-shader/src/emit/lower/global.rs b/crates/victory-shader/src/emit/lower/global.rs deleted file mode 100644 index 52ea4a9..0000000 --- a/crates/victory-shader/src/emit/lower/global.rs +++ /dev/null @@ -1,463 +0,0 @@ -//! Title memory at addresses a program computes ([`GLOBAL`]): pointers it -//! loads, picks by control flow or builds, and the nodes of a BVH it walks. -//! Such an address names no root parameter, so the host binds the address -//! map ([`crate::emit::address_map`]) and a read looks the address up in it -//! (a binary search over its ranges) and loads through the raw view the -//! range names. An address no range covers reads zero. - -use super::*; -use crate::emit::address_map::{ENTRY, HEADER}; -use crate::resource::GLOBAL; - -/// A raw UAV (`RWByteAddressBuffer`): the map's views are UAVs so that the -/// same view serves the program's stores. -const RAW_UAV: (u32, u32) = (11 | 0x1000, 0); - -impl Lower<'_> { - /// Whether the access at `site` reads title memory through the map. - pub(super) fn is_global(&self, site: Site) -> bool { - self.scalar.get(&site).is_some_and(|a| a.param == GLOBAL) - } - - /// `lo | hi << 32`, an i64. - pub(super) fn wide(&mut self, lo: V, hi: V) -> V { - let c = self.cur; - let t = self.s.m.int(64); - self.s.flags |= flags::INT64; - let lo = self.s.m.cast(c, Cast::ZExt, lo, t); - let hi = self.s.m.cast(c, Cast::ZExt, hi, t); - let k = self.s.m.int_const(t, 32); - let hi = self.s.m.bin(c, Bin::Shl, hi, k); - self.s.m.bin(c, Bin::Or, hi, lo) - } - - /// `x` (an i32) widened to i64, sign-extended when `signed`. - pub(super) fn widen(&mut self, x: V, signed: bool) -> V { - let t = self.s.m.int(64); - let op = if signed { Cast::SExt } else { Cast::ZExt }; - self.s.m.cast(self.cur, op, x, t) - } - - /// `n` (at most 4) dwords of the address map from byte `at`. - fn map_dwords(&mut self, at: V, n: u32) -> Vec { - let h = self.s.address_map_handle(); - self.raw_dwords(h, at, n) - } - - /// `n` (at most 4) dwords of raw buffer `h` from byte `at`. - pub(super) fn raw_dwords(&mut self, h: V, at: V, n: u32) -> Vec { - debug_assert!((1..=4).contains(&n)); - let c = self.cur; - let (u, mask, al) = ( - self.s.m.undef(self.s.t.i32), - self.s.m.i8((1 << n) - 1), - self.s.m.i32(4), - ); - let r = self.s.op( - c, - "rawBufferLoad.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 139, - &[h, at, u, mask, al], - ); - (0..n) - .map(|k| { - let x = self.s.m.extract(self.cur, r, k); - self.as_int(x) - }) - .collect() - } - - /// Looks up title address `va` (an i64) in the address map: whether a - /// range covers it, the heap index of the range's view, and the byte - /// in that view `va` is at. - pub(super) fn map_lookup(&mut self, va: V) -> (V, V, V) { - let i32t = self.s.t.i32; - let zero = self.s.m.i32(0); - let count = self.map_dwords(zero, 1)[0]; - // The last range starting at or below `va`: halve the candidates - // [lo, lo + len) until one is left. - let pre = self.cur; - let (head, body, done) = ( - self.s.m.new_block(), - self.s.m.new_block(), - self.s.m.new_block(), - ); - self.s.m.terminate(pre, Term::Br(head)); - let lo = self.s.m.phi(head, i32t); - let len = self.s.m.phi(head, i32t); - let one = self.s.m.i32(1); - let more = self.s.m.cmp(head, pred::IUGT, len, one); - self.s.m.terminate(head, Term::CondBr(more, body, done)); - self.cur = body; - let half = self.s.m.bin(body, Bin::LShr, len, one); - let mid = self.s.m.bin(body, Bin::Add, lo, half); - let start = self.entry_dwords(mid, 0, 2); - let start = self.wide(start[0], start[1]); - let below = self.s.m.cmp(self.cur, pred::IULE, start, va); - let next_lo = self.s.m.select(self.cur, below, mid, lo); - let next_len = self.s.m.bin(self.cur, Bin::Sub, len, half); - let tail = self.cur; - self.s.m.terminate(tail, Term::Br(head)); - self.s.m.set_phi(lo, vec![(zero, pre), (next_lo, tail)]); - self.s.m.set_phi(len, vec![(count, pre), (next_len, tail)]); - self.cur = done; - let e = self.entry_dwords(lo, 0, 4); - let view_offset = self.entry_dwords(lo, 16, 1)[0]; - let c = self.cur; - let start = self.wide(e[0], e[1]); - let rel = self.s.m.bin(c, Bin::Sub, va, start); - let size = self.widen(e[2], false); - let some = self.s.m.cmp(c, pred::NE, count, zero); - let after = self.s.m.cmp(c, pred::IUGE, va, start); - let inside = self.s.m.cmp(c, pred::IULT, rel, size); - let hit = self.s.m.bin(c, Bin::And, after, inside); - let hit = self.s.m.bin(c, Bin::And, hit, some); - let rel = self.s.m.cast(c, Cast::Trunc, rel, i32t); - let byte = self.s.m.bin(c, Bin::Add, rel, view_offset); - (hit, e[3], byte) - } - - /// Dwords `first / 4..` (`n`, at most 4) of map entry `index`. - fn entry_dwords(&mut self, index: V, first: u32, n: u32) -> Vec { - let c = self.cur; - let size = self.s.m.i32(ENTRY); - let at = self.s.m.bin(c, Bin::Mul, index, size); - let base = self.s.m.i32(HEADER + first); - let at = self.s.m.bin(c, Bin::Add, at, base); - self.map_dwords(at, n) - } - - /// `n` dwords of title memory from address `va` (an i64), zero where - /// no range of the map covers `va`. `uniform`: the same address in - /// every lane (a scalar load). The dwords are taken to lie in the range - /// that holds the first. - pub(super) fn global_read(&mut self, va: V, n: u32, uniform: bool) -> Vec { - let (hit, view, byte) = self.map_lookup(va); - let at = self.begin_guarded(Some(hit)); - let h = self.s.heap_handle(self.cur, view, false, !uniform, RAW_UAV); - let mut out = Vec::with_capacity(n as usize); - let mut k = 0; - while k < n { - let chunk = (n - k).min(4); - let off = self.s.m.i32(4 * k); - let from = self.s.m.bin(self.cur, Bin::Add, byte, off); - out.extend(self.raw_dwords(h, from, chunk)); - k += chunk; - } - let zero = self.s.m.i32(0); - let pairs: Vec<(V, V)> = out.iter().map(|&x| (x, zero)).collect(); - self.end_guarded(at, &pairs) - } - - /// `s_load_dword*` from an address the program computes. - pub(super) fn global_smem(&mut self, inst: &Inst) -> Result<(), Why> { - let Fields::Smem { - base, - data, - offset, - soffset, - .. - } = &inst.fields - else { - unreachable!() - }; - let count = match inst.name().strip_prefix("s_load_dword") { - Some("") => 1, - Some("x2") => 2, - Some("x4") => 4, - Some("x8") => 8, - Some("x16") => 16, - _ => return Err("a scalar access to title memory"), - }; - let (Operand::Scalar { code: b, .. }, Some(Operand::Scalar { code: d, .. })) = - (*base, *data) - else { - return Err("a scalar load from title memory"); - }; - let lo = inst.read(Reg::S(b)).ok_or("an unread address")?; - let hi = inst.read(Reg::S(b + 1)).ok_or("an unread address")?; - let (lo, hi) = (self.i32_of(lo)?, self.i32_of(hi)?); - let mut va = self.wide(lo, hi); - let c = self.cur; - let imm = self.s.m.i32(*offset as u32); - let imm = self.widen(imm, true); - va = self.s.m.bin(c, Bin::Add, va, imm); - if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { - let so = self.operand(inst, soffset)?; - let so = self.widen(so, false); - va = self.s.m.bin(self.cur, Bin::Add, va, so); - } - // Scalar loads ignore the address's two low bits. - let t = self.s.m.int(64); - let aligned = self.s.m.int_const(t, !3); - va = self.s.m.bin(self.cur, Bin::And, va, aligned); - let vals = self.global_read(va, count, true); - for (k, x) in vals.into_iter().enumerate() { - self.write(inst, Reg::S(d + k as u8), x, None); - } - Ok(()) - } - - /// The address a `global_*` instruction accesses: its SGPR base plus - /// its VGPR offset, or its VGPR pair, plus its immediate (an i64). - pub(super) fn global_address(&mut self, inst: &Inst) -> Result { - let Fields::Flat { - addr, - saddr, - offset, - .. - } = &inst.fields - else { - unreachable!() - }; - let Some(Operand::Vector { reg, .. }) = *addr else { - return Err("a global address not in VGPRs"); - }; - let vreg = |l: &mut Self, r: u8| -> Result { - let v = inst.read(Reg::V(r)).ok_or("an unread address")?; - l.i32_of(v) - }; - let va = match *saddr { - Some(Operand::Scalar { code, .. }) if code != NULL => { - let lo = inst.read(Reg::S(code)).ok_or("an unread address")?; - let hi = inst.read(Reg::S(code + 1)).ok_or("an unread address")?; - let (lo, hi) = (self.i32_of(lo)?, self.i32_of(hi)?); - let base = self.wide(lo, hi); - let v = vreg(self, reg)?; - let v = self.widen(v, false); - self.s.m.bin(self.cur, Bin::Add, base, v) - } - _ => { - let (lo, hi) = (vreg(self, reg)?, vreg(self, reg + 1)?); - self.wide(lo, hi) - } - }; - let imm = self.s.m.i32(*offset as i32 as u32); - let imm = self.widen(imm, true); - Ok(self.s.m.bin(self.cur, Bin::Add, va, imm)) - } - - /// `global_load_*` from an address the program computes. - pub(super) fn global_load(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { - let Fields::Flat { dst, .. } = &inst.fields else { - unreachable!() - }; - let (n, sub) = match inst.name().strip_prefix("global_load_") { - Some("dword") => (1, None), - Some("dwordx2") => (2, None), - Some("dwordx3") => (3, None), - Some("dwordx4") => (4, None), - Some("ubyte") => (1, Some((8, false))), - Some("sbyte") => (1, Some((8, true))), - Some("ushort") => (1, Some((16, false))), - Some("sshort") => (1, Some((16, true))), - _ => return Err("a global access to title memory"), - }; - let Some(Operand::Vector { reg, .. }) = *dst else { - return Err("a global load result"); - }; - let guard = self.guard(b, i)?; - let va = self.global_address(inst)?; - let vals = match sub { - None => self.global_read(va, n, false), - Some((width, signed)) => { - // shortcut: the field is taken not to cross a dword. - let t = self.s.m.int(64); - let aligned = self.s.m.int_const(t, !3); - let at = self.s.m.bin(self.cur, Bin::And, va, aligned); - let w = self.global_read(at, 1, false)[0]; - let c = self.cur; - let i32t = self.s.t.i32; - let low = self.s.m.cast(c, Cast::Trunc, va, i32t); - let three = self.s.m.i32(3); - let byte = self.s.m.bin(c, Bin::And, low, three); - let sh = self.s.m.bin(c, Bin::Shl, byte, three); - let x = self.s.m.bin(c, Bin::LShr, w, sh); - let left = self.s.m.i32(32 - width); - let x = self.s.m.bin(c, Bin::Shl, x, left); - let op = if signed { Bin::AShr } else { Bin::LShr }; - vec![self.s.m.bin(c, op, x, left)] - } - }; - for (k, x) in vals.into_iter().enumerate() { - self.write(inst, Reg::V(reg + k as u8), x, guard); - } - Ok(()) - } - - /// The VGPR dwords `n` from `reg` that `inst` reads. - fn data_dwords(&mut self, inst: &Inst, reg: u8, n: u32) -> Result, Why> { - (0..n) - .map(|k| { - let v = inst - .read(Reg::V(reg + k as u8)) - .ok_or("an unread store operand")?; - self.i32_of(v) - }) - .collect() - } - - /// `global_store_dword*` to an address the program computes. Lanes - /// whose address no range covers store nothing. - pub(super) fn global_store(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { - let Fields::Flat { data, .. } = &inst.fields else { - unreachable!() - }; - let n = match inst.name().strip_prefix("global_store_") { - Some("dword") => 1, - Some("dwordx2") => 2, - Some("dwordx3") => 3, - Some("dwordx4") => 4, - _ => return Err("a byte or half store to title memory"), - }; - let Some(Operand::Vector { reg, .. }) = *data else { - return Err("a global store's data"); - }; - let vals = self.data_dwords(inst, reg, n)?; - let guard = self.guard(b, i)?; - let va = self.global_address(inst)?; - let (hit, view, byte) = self.map_lookup(va); - let go = match guard { - Some(g) => self.s.m.bin(self.cur, Bin::And, hit, g), - None => hit, - }; - let at = self.begin_guarded(Some(go)); - let h = self.s.heap_handle(self.cur, view, false, true, RAW_UAV); - let iu = self.s.m.undef(self.s.t.i32); - let mut args = vec![h, byte, iu]; - args.extend(&vals); - args.resize(3 + 4, iu); - args.push(self.s.m.i8((1u8 << n) - 1)); - args.push(self.s.m.i32(4)); - let void = self.s.t.void; - self.s.op( - self.cur, - "rawBufferStore.i32", - Attr::NoUnwind, - void, - 140, - &args, - ); - self.end_guarded(at, &[]); - Ok(()) - } - - /// `global_atomic_*` (32-bit) at an address the program computes. A - /// lane whose address no range covers changes nothing and gets 0. - pub(super) fn global_atomic(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { - let Fields::Flat { data, dst, .. } = &inst.fields else { - unreachable!() - }; - // DXIL's atomic operations; cmpswap is u32::MAX. - let op = match inst.name().strip_prefix("global_atomic_") { - Some("add") => 0, - Some("and") => 1, - Some("or") => 2, - Some("xor") => 3, - Some("smin") => 4, - Some("smax") => 5, - Some("umin") => 6, - Some("umax") => 7, - Some("swap") => 8, - Some("sub") => u32::MAX - 1, - Some("cmpswap") => u32::MAX, - _ => return Err("a global atomic of that kind"), - }; - let Some(Operand::Vector { reg, .. }) = *data else { - return Err("a global atomic's data"); - }; - let vals = self.data_dwords(inst, reg, if op == u32::MAX { 2 } else { 1 })?; - let guard = self.guard(b, i)?; - let va = self.global_address(inst)?; - let (hit, view, byte) = self.map_lookup(va); - let go = match guard { - Some(g) => self.s.m.bin(self.cur, Bin::And, hit, g), - None => hit, - }; - let at = self.begin_guarded(Some(go)); - let h = self.s.heap_handle(self.cur, view, false, true, RAW_UAV); - let iu = self.s.m.undef(self.s.t.i32); - let i32t = self.s.t.i32; - let r = if op == u32::MAX { - // Data is (new, compare). - let args = [h, byte, iu, iu, vals[1], vals[0]]; - self.s.op( - self.cur, - "atomicCompareExchange.i32", - Attr::NoUnwind, - i32t, - 79, - &args, - ) - } else { - let (op, x) = if op == u32::MAX - 1 { - let zero = self.s.m.i32(0); - (0, self.s.m.bin(self.cur, Bin::Sub, zero, vals[0])) - } else { - (op, vals[0]) - }; - let opv = self.s.m.i32(op); - let args = [h, opv, byte, iu, iu, x]; - self.s - .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) - }; - let zero = self.s.m.i32(0); - let r = self.end_guarded(at, &[(r, zero)])[0]; - if let Some(Operand::Vector { reg, .. }) = *dst { - self.write(inst, Reg::V(reg), r, guard); - } - Ok(()) - } - - /// The console words of the `count` dwords the descriptor load at - /// `site` reads, from the descriptor words the host binds: a table's - /// user data is the byte offset of its first descriptor in the view - /// heap (32 bytes each, as the console's), the heap's own base 0. - pub(super) fn descriptor_words(&mut self, site: Site, count: u32) -> Result, Why> { - let a = *self - .scalar - .get(&site) - .ok_or("an untracked descriptor load")?; - let rp = *self - .x - .native - .layout - .get(a.param) - .ok_or("a descriptor read as data from no table")?; - let samplers = self - .x - .native - .used - .iter() - .any(|u| u.slot == rp.slot && u.kind == ResourceType::Sampler); - let base = match rp.root { - RootType::Table if !samplers => match self.user(a.param, 0) { - Val::I32(x) => x, - Val::Missing(why) => return Err(why), - Val::Bit(_) => return Err("a table offset"), - }, - RootType::ResourceHeap => self.s.m.i32(0), - _ => return Err("a sampler descriptor read as data"), - }; - let c = self.cur; - let off = self.s.m.i32(a.offset); - let mut byte = self.s.m.bin(c, Bin::Add, base, off); - if let Some(d) = a.dynamic { - let d = self.i32_of(d)?; - byte = self.s.m.bin(self.cur, Bin::Add, byte, d); - } - let h = self.s.descriptor_words_handle(); - let mut out = Vec::with_capacity(count as usize); - let mut k = 0; - while k < count { - let chunk = (count - k).min(4); - let four = self.s.m.i32(4 * k); - let at = self.s.m.bin(self.cur, Bin::Add, byte, four); - out.extend(self.raw_dwords(h, at, chunk)); - k += chunk; - } - Ok(out) - } -} diff --git a/crates/victory-shader/src/emit/lower/mesh_emu.rs b/crates/victory-shader/src/emit/lower/mesh_emu.rs deleted file mode 100644 index 86f5eb0..0000000 --- a/crates/victory-shader/src/emit/lower/mesh_emu.rs +++ /dev/null @@ -1,415 +0,0 @@ -fn mesh_emu_state(ms: &crate::native::MeshIo, x: &Parts) -> MeshEmuState { - let (vertex_offsets, vertex_dwords) = pack_offsets(&x.outputs); - let (prim_offsets, prim_dwords) = pack_offsets(&x.prims); - MeshEmuState { - threads: ms.threads, - max_vertices: ms.max_vertices, - max_primitives: ms.max_primitives, - topology: ms.topology, - vertex_sigs: x.outputs.clone(), - vertex_offsets, - vertex_dwords, - prim_sigs: x.prims.clone(), - prim_offsets, - prim_dwords, - reads_group_id: false, - vals: None, - } -} - -struct MeshEmuVals { - uav: V, - local_group: V, - group_base: V, - flat_lt_verts: Option, - flat_lt_prims: Option, - index_bytes: u32, - vertex_stride_bytes: u32, - prim_offset_bytes: u32, - prim_stride_bytes: u32, -} - -struct MeshEmuState { - threads: u32, - max_vertices: u32, - max_primitives: u32, - topology: u8, - vertex_sigs: Vec, - vertex_offsets: Vec, - vertex_dwords: u32, - prim_sigs: Vec, - prim_offsets: Vec, - prim_dwords: u32, - reads_group_id: bool, - vals: Option, -} - -fn pack_offsets(sigs: &[SigElement]) -> (Vec, u32) { - let mut offsets = Vec::with_capacity(sigs.len()); - let mut next = 0u32; - for e in sigs { - offsets.push(next); - next += u32::from(e.cols); - } - (offsets, next) -} - - -impl MeshEmuState { - fn finish(self) -> super::MeshEmu { - let to_outputs = |sigs: Vec, offsets: Vec| { - sigs.into_iter() - .zip(offsets) - .map(|(s, dword_offset)| super::MeshOutput { - name: s.name, - index: s.index, - kind: s.kind, - comp: s.comp, - interp: s.interp, - row: s.row, - col: s.col, - cols: s.cols, - dword_offset, - }) - .collect() - }; - super::MeshEmu { - threads: self.threads, - max_vertices: self.max_vertices, - max_primitives: self.max_primitives, - vertex_dwords: self.vertex_dwords, - prim_dwords: self.prim_dwords, - reads_group_id: self.reads_group_id, - vertex_outputs: to_outputs(self.vertex_sigs, self.vertex_offsets), - prim_outputs: to_outputs(self.prim_sigs, self.prim_offsets), - } - } -} - -impl<'a> Lower<'a> { - fn mesh_emu_init(&mut self) -> Result<(), Why> { - let (threads, raw_verts, raw_prims, topology, vertex_dwords, prim_dwords) = { - let m = self.mesh_emu.as_ref().expect("mesh emu"); - ( - m.threads, - m.max_vertices, - m.max_primitives, - m.topology, - m.vertex_dwords, - m.prim_dwords, - ) - }; - if topology != 2 { - return Err("a mesh shader not drawing triangles"); - } - if threads == 0 || threads > 1024 || raw_verts > 256 || raw_prims > 256 { - return Err("a mesh shader beyond the host's limits"); - } - let max_vertices = raw_verts.min(threads); - let max_primitives = raw_prims.min(threads); - if max_vertices == 0 || max_primitives == 0 { - return Err("an empty mesh shader output"); - } - let index_bytes = max_primitives * 4; - let vertex_stride_bytes = vertex_dwords * 4; - let prim_offset_bytes = index_bytes + max_vertices * vertex_stride_bytes; - let prim_stride_bytes = prim_dwords * 4; - let group_bytes = prim_offset_bytes + max_primitives * prim_stride_bytes; - - let e = self.s.entry; - let i32t = self.s.t.i32; - let uav = self.s.emu_uav_handle(); - let k0 = self.s.m.i32(0); - let local_group = self.s.op(e, "groupId.i32", Attr::ReadNone, i32t, 94, &[k0]); - let flat = self.mesh_thread(); - let group_stride = self.s.m.i32(group_bytes); - let group_base = self.s.m.bin(e, Bin::Mul, local_group, group_stride); - let flat_lt_verts = (threads > max_vertices).then(|| { - let mv = self.s.m.i32(max_vertices); - self.s.m.cmp(e, pred::IULT, flat, mv) - }); - let flat_lt_prims = (threads > max_primitives).then(|| { - let mp = self.s.m.i32(max_primitives); - self.s.m.cmp(e, pred::IULT, flat, mp) - }); - let m = self.mesh_emu.as_mut().expect("mesh emu"); - m.max_vertices = max_vertices; - m.max_primitives = max_primitives; - m.vals = Some(MeshEmuVals { - uav, - local_group, - group_base, - flat_lt_verts, - flat_lt_prims, - index_bytes, - vertex_stride_bytes, - prim_offset_bytes, - prim_stride_bytes, - }); - Ok(()) - } - - /// Initializes every primitive index word in the group slice as culled - /// (`bit 31 = 1`) so unexported slots never draw stale data. - fn mesh_emu_prologue(&mut self) { - let (uav, group_base, flat_lt_prims) = { - let v = self - .mesh_emu - .as_ref() - .expect("mesh emu") - .vals - .as_ref() - .expect("mesh emu init"); - (v.uav, v.group_base, v.flat_lt_prims) - }; - let flat = self.mesh_thread(); - let at = self.begin_guarded(flat_lt_prims); - let c = self.cur; - let k2 = self.s.m.i32(2); - let byte_off = self.s.m.bin(c, Bin::Shl, flat, k2); - let addr = self.s.m.bin(c, Bin::Add, group_base, byte_off); - let undef = self.s.m.undef(self.s.t.i32); - let culled = self.s.m.i32(0x8000_0000); - let mask1 = self.s.m.i8(1); - let align4 = self.s.m.i32(4); - let void = self.s.t.void; - self.s.op( - c, - "rawBufferStore.i32", - Attr::NoUnwind, - void, - 140, - &[uav, addr, undef, culled, undef, undef, undef, mask1, align4], - ); - self.end_guarded(at, &[]); - } - - fn combine_guards(&mut self, a: Option, b: Option) -> Option { - match (a, b) { - (Some(x), Some(y)) => Some(self.s.m.bin(self.cur, Bin::And, x, y)), - (Some(x), None) | (None, Some(x)) => Some(x), - (None, None) => None, - } - } - - /// Emulated mesh: `exp prim` writes the packed primitive index word - /// (preserving bit 31 as the cull flag) to `u0, space 2`. - fn emit_indices_emu(&mut self, e: &Export, guard: Option) -> Result<(), Why> { - let v = e.values[0].ok_or("a primitive export without its indices")?; - let x = self.i32_of(v)?; - let (uav, group_base, flat_lt_prims) = { - let v = self - .mesh_emu - .as_ref() - .expect("mesh emu") - .vals - .as_ref() - .expect("mesh emu init"); - (v.uav, v.group_base, v.flat_lt_prims) - }; - let guard = self.combine_guards(guard, flat_lt_prims); - let flat = self.mesh_thread(); - let at = self.begin_guarded(guard); - let c = self.cur; - let k2 = self.s.m.i32(2); - let byte_off = self.s.m.bin(c, Bin::Shl, flat, k2); - let addr = self.s.m.bin(c, Bin::Add, group_base, byte_off); - let undef = self.s.m.undef(self.s.t.i32); - let mask1 = self.s.m.i8(1); - let align4 = self.s.m.i32(4); - let void = self.s.t.void; - self.s.op( - c, - "rawBufferStore.i32", - Attr::NoUnwind, - void, - 140, - &[uav, addr, undef, x, undef, undef, undef, mask1, align4], - ); - self.end_guarded(at, &[]); - Ok(()) - } - - /// Emulated mesh: stores vertex (`primitive == false`) or per-primitive - /// (`primitive == true`) exported scalars into `u0, space 2`, coalescing - /// contiguous dword slots up to 4 dwords per store. - fn store_mesh_emu_outputs( - &mut self, - guard: Option, - primitive: bool, - stores: &[(usize, u8, Value, Option)], - ) -> Result<(), Why> { - if stores.is_empty() { - return Ok(()); - } - let mut items: Vec<(u32, V, Option)> = Vec::with_capacity(stores.len()); - for &(id, col, value, half) in stores { - let x = self.i32_of(value)?; - let slot = { - let m = self.mesh_emu.as_mut().expect("mesh emu"); - let (sigs, offsets) = if primitive { - (&mut m.prim_sigs, &m.prim_offsets) - } else { - (&mut m.vertex_sigs, &m.vertex_offsets) - }; - sigs[id].usage |= 1 << col; - offsets[id] + u32::from(col) - }; - items.push((slot, x, half)); - } - items.sort_by_key(|&(slot, _, _)| slot); - let mut deduped: Vec<(u32, V, Option)> = Vec::with_capacity(items.len()); - for item in items { - if let Some(last) = deduped.last_mut() - && last.0 == item.0 - { - *last = item; - } else { - deduped.push(item); - } - } - let (uav, group_base, bound_guard, base_offset, stride_bytes) = { - let v = self - .mesh_emu - .as_ref() - .expect("mesh emu") - .vals - .as_ref() - .expect("mesh emu init"); - if primitive { - ( - v.uav, - v.group_base, - v.flat_lt_prims, - v.prim_offset_bytes, - v.prim_stride_bytes, - ) - } else { - ( - v.uav, - v.group_base, - v.flat_lt_verts, - v.index_bytes, - v.vertex_stride_bytes, - ) - } - }; - let guard = self.combine_guards(guard, bound_guard); - let flat = self.mesh_thread(); - let at = self.begin_guarded(guard); - let c = self.cur; - let mut converted = Vec::with_capacity(deduped.len()); - for (slot, mut x, half) in deduped { - if let Some(high) = half { - if high { - let k16 = self.s.m.i32(16); - x = self.s.m.bin(c, Bin::LShr, x, k16); - } - let f32t = self.s.t.f32; - let f = self - .s - .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); - x = self.as_int(f); - } - converted.push((slot, x)); - } - let stride = self.s.m.i32(stride_bytes); - let rel = self.s.m.bin(c, Bin::Mul, flat, stride); - let off = if base_offset == 0 { - rel - } else { - let base_k = self.s.m.i32(base_offset); - self.s.m.bin(c, Bin::Add, base_k, rel) - }; - let rec_base = self.s.m.bin(c, Bin::Add, group_base, off); - let undef = self.s.m.undef(self.s.t.i32); - let align4 = self.s.m.i32(4); - let void = self.s.t.void; - let mut idx = 0; - while idx < converted.len() { - let start_slot = converted[idx].0; - let mut len = 1usize; - while len < 4 - && idx + len < converted.len() - && converted[idx + len].0 == start_slot + len as u32 - { - len += 1; - } - let addr = if start_slot == 0 { - rec_base - } else { - let disp = self.s.m.i32(start_slot * 4); - self.s.m.bin(c, Bin::Add, rec_base, disp) - }; - let v0 = converted[idx].1; - let v1 = if len > 1 { converted[idx + 1].1 } else { undef }; - let v2 = if len > 2 { converted[idx + 2].1 } else { undef }; - let v3 = if len > 3 { converted[idx + 3].1 } else { undef }; - let mask = self.s.m.i8((1u8 << len) - 1); - self.s.op( - c, - "rawBufferStore.i32", - Attr::NoUnwind, - void, - 140, - &[uav, addr, undef, v0, v1, v2, v3, mask, align4], - ); - idx += len; - } - self.end_guarded(at, &[]); - Ok(()) - } - fn mesh_group_emu(&mut self) -> Val { - let m = self.mesh_emu.as_mut().expect("mesh emu"); - m.reads_group_id = true; - let local_group = m.vals.as_ref().expect("mesh emu init").local_group; - let cbv = self.s.emu_cbv_handle(); - let srv = self.s.emu_srv_handle(); - let c = self.cur; - let i32t = self.s.t.i32; - let k0 = self.s.m.i32(0); - let base_ret = self.s.op( - c, - "cbufferLoadLegacy.i32", - Attr::ReadOnly, - self.s.t.cbuf_ret, - 59, - &[cbv, k0], - ); - let base = self.s.m.extract(c, base_ret, 0); - let flag = self.s.m.i32(super::INDIRECT_SLOT_MAP_FLAG); - let is_map = self.s.m.cmp(c, pred::EQ, base, flag); - let map_bb = self.s.m.new_block(); - let add_bb = self.s.m.new_block(); - let join_bb = self.s.m.new_block(); - self.s.m.terminate(c, Term::CondBr(is_map, map_bb, add_bb)); - - let k2 = self.s.m.i32(2); - let off = self.s.m.bin(map_bb, Bin::Shl, local_group, k2); - let undef = self.s.m.undef(i32t); - let mask1 = self.s.m.i8(1); - let align4 = self.s.m.i32(4); - let r = self.s.op( - map_bb, - "rawBufferLoad.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 139, - &[srv, off, undef, mask1, align4], - ); - let f = self.s.m.extract(map_bb, r, 0); - let g_map = self.s.m.cast(map_bb, Cast::Bitcast, f, i32t); - self.s.m.terminate(map_bb, Term::Br(join_bb)); - - let g_add = self.s.m.bin(add_bb, Bin::Add, local_group, base); - self.s.m.terminate(add_bb, Term::Br(join_bb)); - - let g = self.s.m.phi(join_bb, i32t); - self.s.m.set_phi(g, vec![(g_map, map_bb), (g_add, add_bb)]); - let n = self.s.m.i32(self.x.mesh_stride); - let res = self.s.m.bin(join_bb, Bin::Mul, g, n); - self.cur = join_bb; - Val::I32(res) - } - -} diff --git a/crates/victory-shader/src/emit/lower/methods.rs b/crates/victory-shader/src/emit/lower/methods.rs deleted file mode 100644 index baa4a83..0000000 --- a/crates/victory-shader/src/emit/lower/methods.rs +++ /dev/null @@ -1,639 +0,0 @@ -impl<'a> Lower<'a> { - fn exit(&mut self, b: usize) -> Result<(), Stop> { - let offset = self.x.p.blocks[b] - .insts - .last() - .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset); - self.cur_reads.clear(); - self.cur_old_deps.clear(); - self.cur_edge = None; - let term = match self.x.st.exits[b] { - LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => { - let ok = self.count_iteration(t, pred::IULT); - let abort = self.abort_block(); - Term::CondBr(ok, self.block[t].expect("reachable"), abort) - } - LaneExit::Jump(t) => { - self.enter_loop(b, t, self.cur); - Term::Br(self.block[t].expect("reachable")) - } - LaneExit::Branch { - when, - taken, - not_taken, - } => { - // A negated condition branches the other way round. - let (cond, taken, not_taken) = match self.x.st.bools.node(when) { - _ if self.x.st.wide.contains(&b) => { - let c = self - .wave_wide(b, when) - .map_err(|w| unsupported(offset, w))?; - (c, taken, not_taken) - } - Some((atom, Bool::TRUE, Bool::FALSE)) => { - let a = self - .atom(atom, self.cur) - .map_err(|w| unsupported(offset, w))?; - (a, not_taken, taken) - } - _ => { - let c = self - .boolean(when, self.cur) - .map_err(|w| unsupported(offset, w))?; - (c, taken, not_taken) - } - }; - let reads = std::mem::take(&mut self.cur_reads); - if !reads.is_empty() { - self.sinks.push(SinkRead { - block: b, - guard: None, - offset, - deps: reads, - }); - } - // A back edge is taken only below the iteration limit. - let back = - |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b]; - // (No `xor` of a compare: a loop exit testing one hung the - // AMD driver.) - let cond = if back(self, taken) { - let ok = self.count_iteration(taken, pred::IULT); - self.s.m.bin(self.cur, Bin::And, cond, ok) - } else if back(self, not_taken) { - let stop = self.count_iteration(not_taken, pred::IUGE); - self.s.m.bin(self.cur, Bin::Or, cond, stop) - } else { - cond - }; - // Critical edges get a block of their own, so loops have - // dedicated exits and preheaders as DXC emits them. - let (t, f) = (self.edge(b, taken), self.edge(b, not_taken)); - for (to, via) in [(taken, t), (not_taken, f)] { - if !back(self, to) { - // From an edge block, or from here. - let from = if Some(via) == self.block[to] { - self.cur - } else { - via - }; - self.enter_loop(b, to, from); - } - } - Term::CondBr(cond, t, f) - } - LaneExit::End => { - if self.s.pixel && !self.exported[b] && !self.has_done_export(b) { - // A lane leaving without its final export was killed. - let t = self.s.m.bool(true); - self.s - .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); - } - Term::Br(self.ret_block()) - } - LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")), - }; - let _ = Exit::End; - self.s.m.terminate(self.cur, term); - Ok(()) - } - - /// A forward edge into loop header `to` (from DXIL block `via`) starts - /// its count at 0. - fn enter_loop(&mut self, _from: usize, to: usize, via: usize) { - if let Some((_, incoming)) = self.counters.get_mut(&to) { - let z = self.s.m.i32(0); - incoming.push((z, via)); - } - } - - /// A back edge to header `to` (a back edge keeps its block, no - /// critical-edge block): the count goes up; the result compares it with - /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop). - fn count_iteration(&mut self, to: usize, p: u8) -> V { - let c = self.cur; - let (phi, _) = self.counters[&to]; - let one = self.s.m.i32(1); - let next = self.s.m.bin(c, Bin::Add, phi, one); - // Per stage unless the switch names one: a loop that never meets its - // exit (a count read from a buffer the host has not got yet, say) - // runs to the limit in every lane. A million iterations a pixel - // hung the GPU for seconds a draw until Windows reset it - // (PS_Textured_Eight, 2026-11-24, run 12). - // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop - // past 256 or a compute loop past 4,096 is cut short. (They were - // 1,024, 4,096 and 65,536: the opening cutscene then lost the card - // 14-25 frames in, in a minimap or shadow mesh draw; with every - // loop cut at 64 it ran 90 frames. Raise them again once shaders - // stop reading data that is not there yet.) - let limit = match super::loop_limit() { - LOOP_LIMIT if self.s.pixel => 1 << 7, - LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8, - LOOP_LIMIT => 1 << 12, - named => named, - }; - let limit = self.s.m.i32(limit); - // The breadcrumb may end the block (a store of one lane), so the - // back edge leaves from where it ends. - self.crumb(to, next); - let c = self.cur; - self.counters - .get_mut(&to) - .expect("header") - .1 - .push((next, c)); - self.s.m.cmp(c, p, next, limit) - } - - /// Breadcrumbs (see [`super::breadcrumbs`]): the count of the loop at - /// header `to` goes to its word of the shader's slot, as the largest - /// any lane reached: the wave's largest, stored by its first active lane - /// (one atomic a wave, not one a lane). The buffer's UAV is the view - /// heap's entry at the index in the first user-data dword past the - /// console's. - #[allow(dead_code)] - fn crumb(&mut self, to: usize, count: V) { - let Some(slot) = self.x.crumbs else { return }; - let next = self.crumb_loops.len() as u32; - let n = *self.crumb_loops.entry(to).or_insert(next); - if n >= super::BREADCRUMB_LOOPS { - return; - } - let first = self - .x - .native - .layout - .iter() - .map(|r| u32::from(r.user_data) + r.sgprs) - .max() - .unwrap_or(0); - let index = self.user_dword(UserData { - index: first, - slot: 0, - root: super::BREADCRUMB_ROOT, - dword: 0, - }); - let c = self.cur; - let (i1, i32t) = (self.s.t.i1, self.s.t.i32); - self.s.flags |= flags::WAVE_OPS; - // The largest count of the lanes that take the back edge (unsigned max). - let (k, u) = (self.s.m.i8(3), self.s.m.i8(1)); - let count = self.s.op( - c, - "waveActiveOp.i32", - Attr::NoUnwind, - i32t, - 119, - &[count, k, u], - ); - let first = self - .s - .op(c, "waveIsFirstLane", Attr::NoUnwind, i1, 110, &[]); - let guarded = self.begin_guarded(Some(first)); - let c = self.cur; - // A raw buffer UAV (`atomicMax`, operation 7, at the word's byte offset). - let h = self.s.heap_handle(c, index, false, false, (11 | 0x1000, 0)); - let at = self.s.m.i32((slot * super::BREADCRUMB_LOOPS + n) * 4); - let (op, unused) = (self.s.m.i32(7), self.s.m.undef(i32t)); - self.s.op( - c, - "atomicBinOp.i32", - Attr::NoUnwind, - i32t, - 78, - &[h, op, at, unused, unused, count], - ); - self.end_guarded(guarded, &[]); - } - - /// The block a lane stopped by [`LOOP_LIMIT`] leaves through. - fn abort_block(&mut self) -> usize { - if let Some(a) = self.abort { - return a; - } - let a = self.s.m.new_block(); - if self.s.pixel { - let t = self.s.m.bool(true); - self.s - .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); - } - let r = self.ret_block(); - self.s.m.terminate(a, Term::Br(r)); - self.abort = Some(a); - a - } - - /// The function's single returning block (see `ret`). - fn ret_block(&mut self) -> usize { - if let Some(r) = self.ret { - return r; - } - let r = self.s.m.new_block(); - self.s.m.terminate(r, Term::Ret); - self.ret = Some(r); - r - } - - /// The DXIL block a branch from IR block `from` to `to` goes to. - fn edge(&mut self, from: usize, to: usize) -> usize { - let target = self.block[to].expect("reachable"); - let preds = self.x.p.blocks[to] - .preds - .iter() - .filter(|&&q| self.block[q].is_some()) - .count(); - // Back edges stay as they are: the exiting block is the latch. - if preds < 2 || self.rpo[to] <= self.rpo[from] { - return target; - } - let e = self.s.m.new_block(); - self.s.m.terminate(e, Term::Br(target)); - self.edges.insert((from, to), e); - e - } - - fn fill_phis(&mut self) -> Result<(), Stop> { - let p = self.x.p; - let data_phis = std::mem::take(&mut self.data_phis); - let mut has_missing = false; - // Lane-mask joins first (what an edge brings may ask for more joins, - // of masks and of numbers): each edge's mask as the structure - // tracked it, a constant or a scalar-built one included. - let st = self.x.st; - while let Some((v, b, i)) = self.pending_masks.pop() { - let phi = &p.blocks[b].phis[i]; - let offset = p.blocks[b].offset; - let args = st - .phi_masks - .get(&phi.value) - .ok_or_else(|| unsupported(offset, "a lane-mask join of an untracked mask"))?; - let mut incoming = Vec::new(); - for (n, &q) in p.blocks[b].preds.iter().enumerate() { - let Some(qb) = self.tail[q] else { continue }; - let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); - let x = self - .boolean(args[n], qb) - .map_err(|w| unsupported(offset, w))?; - incoming.push((x, qb)); - } - self.s.m.set_phi(v, incoming); - } - // A join that only another join reads is read wherever that one is. Left - // unmarked, a value without a DXIL form coming into it became zero without a - // word (the looked-up tint of the material resolve programs, whose size - // computation had no value, was zero in every lane that way). - // shortcut: only with `VICTORY_STRICT_JOINS` set (the offline pack - // listing sets it to count them): 40 programs that translate today - // stop by name with it (vehicle paint pixel shaders at "the first - // half of an interpolation", foliage mesh shaders); until those are - // lowered they keep drawing with that zero. - static STRICT: std::sync::OnceLock = std::sync::OnceLock::new(); - let strict = *STRICT.get_or_init(|| std::env::var_os("VICTORY_STRICT_JOINS").is_some()); - let mut work: Vec = if strict { - self.read_phis.iter().copied().collect() - } else { - Vec::new() - }; - while let Some(v) = work.pop() { - let Some(&(b, i)) = self.phi_at.get(&v) else { - continue; - }; - for &a in &p.blocks[b].phis[i].args { - if self.phi_at.contains_key(&a) && self.read_phis.insert(a) { - work.push(a); - } - } - } - for &(v, b, i) in &data_phis { - let phi = &p.blocks[b].phis[i]; - let bit = phi.reg == Reg::Scc; - // A join of numbers with dead registers (`dead`): the paths that bring those - // never read the result, so they bring zero. Not for a join that is itself a - // lane mask (a ballot gives that one as data). - let st = self.x.st; - let numbers = !bit - && !st.masks.contains_key(&phi.value) - && !st.highs.contains_key(&phi.value) - && phi - .args - .iter() - .any(|a| matches!(self.vals.get(a), Some(Val::I32(_)))); - let mut incoming = Vec::new(); - 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 arg = phi.args[n]; - if self.read_phis.contains(&phi.value) && !self.vals.contains_key(&arg) { - let _ = self.lazy_barycentric(arg); - // A root parameter nothing read before the join (user - // data is loaded on first use, in the entry block). - if !self.vals.contains_key(&arg) - && let Some(&(param, dword)) = self.params.get(&arg) - { - let val = self.user(param, dword); - self.vals.insert(arg, val); - } - } - let x = match (self.vals.get(&arg).copied(), bit) { - (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x, - // A lane mask's dword reaching a join that also takes - // data: the registers are reused once the mask is dead. - // shortcut: undefined on that edge, assuming the program - // reads the joined value only on paths from a data edge. - (Some(Val::Missing(_)), false) - if self.x.st.masks.contains_key(&arg) - || self.x.st.highs.contains_key(&arg) => - { - self.s.m.undef(self.s.t.i32) - } - (Some(Val::Missing(_)) | None, false) - if numbers && self.dead(arg, &mut Vec::new()) => - { - has_missing = true; - self.s.m.i32(0) - } - // A lane mask joined with numbers (a traversal that keeps its lanes' masks on - // a stack with its node numbers): the mask comes as the number it is, the - // ballot of its lanes where it is written. - (Some(Val::Missing(_)) | None, false) - if self.read_phis.contains(&phi.value) - && self.mask_data == MaskData::Console - && (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) => - { - match self.mask_dword(arg) { - Ok(x) => x, - Err(why) => return Err(Stop::Retry(phi.value, why)), - } - } - // SCC of a mask operation ("some lane is left") joined with a scalar test: - // the compiler branches around code that sets SCC and tests SCC after it, - // the skip bringing "no lane" along. As data it is "some lane of the wave - // has the bit" - right only if the wave took that skip together, as the - // console does: a lane that skipped alone would bring "some lane" where the - // console has the skipped code's SCC. So the branch must be one the wave - // takes together; else its region is named for `emit`'s retry to widen it. - (Some(Val::Missing(_)) | None, true) - if self.read_phis.contains(&phi.value) - && self.mask_data == MaskData::Console - && st.scc_some.contains_key(&arg) => - { - let per_lane = !st.wide.contains(&q) - && matches!(st.exits[q], LaneExit::Branch { when, .. } - if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_)))); - if per_lane { - for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) { - need(other); - } - return Err(Stop::Retry(phi.value, LANE_MASK)); - } - match self.scc_some(arg) { - Ok(x) => x, - Err(why) => return Err(Stop::Retry(phi.value, why)), - } - } - (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { - return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); - } - (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => { - return Err(Stop::Retry(phi.value, why)); - } - _ => { - has_missing = true; - if bit { - self.s.m.bool(false) - } else { - self.s.m.i32(0) - } - } - }; - incoming.push((x, qb)); - } - self.s.m.set_phi(v, incoming); - } - for (phi, incoming) in std::mem::take(&mut self.counters).into_values() { - self.s.m.set_phi(phi, incoming); - } - while let Some((v, b, i)) = self.pending_masks.pop() { - let phi = &p.blocks[b].phis[i]; - let offset = p.blocks[b].offset; - let mut incoming = Vec::new(); - 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") - })?; - self.cur_reads.clear(); - self.cur_edge = None; - let x = self.boolean(m, qb).map_err(|w| unsupported(offset, w))?; - let reads = std::mem::take(&mut self.cur_reads); - if !reads.is_empty() { - let deps = reads - .into_iter() - .map(|dep| match dep { - ReadDep::Value(value) => ReadDep::Edge { - from: q, - to: b, - value, - }, - other => other, - }) - .collect(); - self.sinks.push(SinkRead { - block: q, - guard: None, - offset, - deps, - }); - } - incoming.push((x, qb)); - } - self.s.m.set_phi(v, incoming); - } - if (!has_missing && self.direct_missing.is_empty()) || self.sinks.is_empty() { - return Ok(()); - } - self.check_missing_reach(&data_phis) - } - - /// Rejects the program if any missing or mismatched phi incoming edge (or - /// direct missing value surviving via a partial/guarded overwrite) can - /// reach an observable sink along a feasible path in [`Structured`]. - fn check_missing_reach(&self, data_phis: &[(V, usize, usize)]) -> Result<(), Stop> { - const MAX_TAINT_ROUNDS: usize = 256; - let p = self.x.p; - let st = self.x.st; - let mut bools = BoolSet::new(&st.bools); - let mut taint: HashMap> = HashMap::new(); - - let site_cond = - |bools: &mut BoolSet, block: usize, guard: Option, invert: bool| -> Bool { - match guard { - Some(g) => { - let g = if invert { bools.not(g) } else { g }; - bools.and(st.reach[block], g) - } - None => st.reach[block], - } - }; - let dep_cond = |bools: &mut BoolSet, base: Bool, dep: ReadDep| -> (Value, Bool) { - match dep { - ReadDep::Value(u) => (u, base), - ReadDep::Edge { from, to, value: u } => { - let ec = bools.edge(st, from, to); - (u, bools.and(base, ec)) - } - } - }; - let merge = |taint: &mut HashMap>, - dst: Value, - why: Why, - cond: Bool, - bools: &mut BoolSet| - -> bool { - if cond == Bool::FALSE { - return false; - } - let list = taint.entry(dst).or_default(); - if let Some((_, existing)) = list.iter_mut().find(|(w, _)| *w == why) { - let next = bools.or(*existing, cond); - if next != *existing { - *existing = next; - return true; - } - false - } else { - list.push((why, cond)); - true - } - }; - - for &(dst, why, block, guard, invert) in &self.direct_missing { - let c = site_cond(&mut bools, block, guard, invert); - merge(&mut taint, dst, why, c, &mut bools); - } - - for &(_, b, i) in data_phis { - let phi = &p.blocks[b].phis[i]; - let bit = phi.reg == Reg::Scc; - for (n, &q) in p.blocks[b].preds.iter().enumerate() { - if self.tail[q].is_none() { - continue; - } - let arg = phi.args[n]; - let why = match (self.vals.get(&arg).copied(), bit) { - (Some(Val::I32(_)), false) | (Some(Val::Bit(_)), true) => continue, - (Some(Val::Bit(_)), false) => "an SCC joined with SGPR values", - (Some(Val::Missing(why)), _) => why, - _ => "a join of mismatched values", - }; - let mut c = bools.edge(st, q, b); - if self.rpo[b] <= self.rpo[q] { - c = bools.forget(c, self.rpo[b]); - } - merge(&mut taint, phi.value, why, c, &mut bools); - } - } - - let propagate_step = - |taint: &mut HashMap>, bools: &mut BoolSet, precise: bool| { - let mut changed = false; - for &(_, b, i) in data_phis { - let phi = &p.blocks[b].phis[i]; - for (n, &q) in p.blocks[b].preds.iter().enumerate() { - if self.tail[q].is_none() { - continue; - } - let Some(list) = taint.get(&phi.args[n]).cloned() else { - continue; - }; - let ec = if precise { - bools.edge(st, q, b) - } else { - Bool::TRUE - }; - for (why, c) in list { - let tc = if precise { - let mut tc = bools.and(c, ec); - if self.rpo[b] <= self.rpo[q] { - tc = bools.forget(tc, self.rpo[b]); - } - tc - } else { - Bool::TRUE - }; - changed |= merge(taint, phi.value, why, tc, bools); - } - } - } - for &w in &self.deps_order { - for info in &self.deps[&w] { - let use_c = if precise { - site_cond(bools, info.block, info.guard, info.invert_guard) - } else { - Bool::TRUE - }; - for &dep in &info.deps { - let (val, dc) = if precise { - dep_cond(bools, use_c, dep) - } else { - let u = match dep { - ReadDep::Value(u) | ReadDep::Edge { value: u, .. } => u, - }; - (u, Bool::TRUE) - }; - let Some(list) = taint.get(&val).cloned() else { - continue; - }; - for (why, c) in list { - if info.ignore_why == Some(why) { - continue; - } - let tc = if precise { - bools.and(c, dc) - } else { - Bool::TRUE - }; - changed |= merge(taint, w, why, tc, bools); - } - } - } - } - changed - }; - - let mut settled = false; - for _ in 0..MAX_TAINT_ROUNDS { - if !propagate_step(&mut taint, &mut bools, true) { - settled = true; - break; - } - } - if !settled { - // Conservative widening when cyclic propagation exceeds the round cap. - for list in taint.values_mut() { - for (_, c) in list.iter_mut() { - *c = Bool::TRUE; - } - } - while propagate_step(&mut taint, &mut bools, false) {} - } - - for sink in &self.sinks { - let sink_c = site_cond(&mut bools, sink.block, sink.guard, false); - for &dep in &sink.deps { - let (val, dc) = dep_cond(&mut bools, sink_c, dep); - if let Some(list) = taint.get(&val) { - for &(why, c) in list { - if bools.sat(c, dc) { - return Err(unsupported(sink.offset, why)); - } - } - } - } - } - Ok(()) - } - -} diff --git a/crates/victory-shader/src/emit/lower/tests.rs b/crates/victory-shader/src/emit/lower/tests.rs deleted file mode 100644 index 643869c..0000000 --- a/crates/victory-shader/src/emit/lower/tests.rs +++ /dev/null @@ -1,1773 +0,0 @@ -use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; -use crate::native::{ - ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, -}; -use crate::{io, ir, resource, structure}; - -const S_ENDPGM: u32 = 0xBF81_0000; - -#[test] -fn packed_pixel_inputs_find_their_second_row() { - use super::super::container::SigElement; - use super::half_input_partners; - use crate::native::{PsInput, Usage}; - let entry = |row, row2, pack2| PsInput { - usage: Usage::Generic, - row, - mask: 0xF, - attr: row, - flat: false, - fp16: true, - pack2, - row2, - }; - let element = |row| SigElement { - name: "TEXCOORD".into(), - index: row, - kind: 0, - comp: 9, - interp: 2, - row: Some(row), - col: 0, - cols: 4, - usage: 0, - half: true, - }; - // Rows 0 and 3 pack and leave their second row out; 5 names its - // own (6). Unnamed 16-bit rows: 1, 4, 6, 7. - let io = StageIo::Ps { - inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)], - input_addr: 0, - db_shader_control: 0, - patches: vec![], - rsrc2: 0, - }; - let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into(); - let p = half_input_partners(&io, &sig); - assert_eq!(p.get(&0), Some(&1)); - assert_eq!(p.get(&3), Some(&4)); - assert_eq!(p.get(&5), None); -} - -/// The packed pedestrian layouts of Grand Theft Auto VI: an element -/// behind another one in its register follows in the first parameter -/// with a dword left, and is not a half of its register's row. -#[test] -fn packed_elements_behind_another_take_the_first_free_dword() { - use super::super::container::SigElement; - use super::packed_half; - let element = |index, row, col, cols| SigElement { - name: "TEXCOORD".into(), - index, - kind: 0, - comp: 9, - interp: 2, - row: Some(row), - col, - cols, - usage: 0, - half: true, - }; - // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel - // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4 - // column 3; parameter 3 (rows 6 and 7) carries it in dword 3. - let sig = vec![ - element(1, 2, 0, 4), - element(2, 3, 0, 4), - element(4, 4, 0, 3), - element(6, 4, 3, 1), - element(3, 5, 0, 4), - element(5, 6, 0, 4), - element(7, 7, 0, 2), - element(9, 9, 0, 3), - element(11, 10, 0, 3), - element(15, 12, 0, 4), - ]; - let packs = [ - (2, Some(3)), - (4, Some(5)), - (6, Some(7)), - (9, Some(10)), - (12, None), - ]; - let at = |a, h| packed_half(&sig, &packs, a, h); - // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3. - assert_eq!(at(4, 2), Some((4, 2))); - assert_eq!(at(4, 3), None); - assert_eq!(at(4, 4), Some((5, 0))); - assert_eq!(at(4, 7), Some((5, 3))); - // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone. - assert_eq!(at(6, 3), Some((6, 3))); - assert_eq!(at(6, 5), Some((7, 1))); - assert_eq!(at(6, 6), Some((4, 3))); - assert_eq!(at(6, 7), None); - // Parameters without such an element are as before. - assert_eq!(at(9, 3), None); - assert_eq!(at(9, 4), Some((10, 0))); - assert_eq!(at(12, 3), Some((12, 3))); - assert_eq!(at(12, 4), None); - // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at - // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1, - // TEXCOORD7. - let sig = vec![ - element(0, 1, 0, 2), - element(7, 1, 2, 2), - element(1, 2, 0, 4), - element(2, 3, 0, 4), - element(4, 4, 0, 3), - ]; - let packs = [(3, Some(4)), (1, Some(2))]; - let at = |a, h| packed_half(&sig, &packs, a, h); - assert_eq!(at(1, 1), Some((1, 1))); - assert_eq!(at(1, 2), Some((2, 0))); - assert_eq!(at(1, 5), Some((2, 3))); - assert_eq!(at(1, 6), Some((1, 2))); - assert_eq!(at(1, 7), Some((1, 3))); - assert_eq!(at(3, 6), Some((4, 2))); - assert_eq!(at(3, 7), None); - // A row no element holds gives nothing, as before. - assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None); -} - -/// Whether a synthetic compute program translates with these input registers. -fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - crumbs: None, - emulate_mesh: false, - }) - .map(|_| ()) -} - -/// Lowers a compute program with the root parameters `layout` (in user -/// SGPRs from s0 on) and the used resources `used`. -fn lower_with( - words: &[u32], - layout: Vec, - used: Vec, -) -> Result { - lower_wave(words, layout, used, false) -} - -/// [`lower_with`] in wave64 if `wave64`. -fn lower_wave( - words: &[u32], - layout: Vec, - used: Vec, - wave64: bool, -) -> Result { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64, - vgprs: 256, - layout, - used, - io: StageIo::Cs(ComputeIo { - // The layout's user SGPRs (at least two), 512 bytes of LDS. - rsrc2: 1 << 15 | sgprs.max(2) << 1, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, wave64, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - crumbs: None, - emulate_mesh: false, - }) -} - -/// A counted loop (`s5` from 0 to 4) in a compute program with one root -/// constant in `s0`, lowered with breadcrumbs for `crumbs`. -fn counted_loop(crumbs: Option) -> Lowered { - let words = [ - 0xBE85_0380u32, // s_mov_b32 s5, 0 - 0x8005_8105, // s_add_u32 s5, s5, 1 - 0xBF0A_8405, // s_cmp_lt_u32 s5, 4 - 0xBF85_FFFD, // s_cbranch_scc1 -3 - S_ENDPGM, - ]; - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![root(RootType::Constants, 0, 0)], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 1 << 15 | 2 << 1, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - emulate_mesh: false, - crumbs, - }) - .unwrap() -} - -#[test] -fn breadcrumbs_add_a_loop_store_and_one_user_data_dword() { - let plain = counted_loop(None); - assert!( - plain - .user_data - .iter() - .all(|u| u.root != crate::emit::BREADCRUMB_ROOT) - ); - let crumbs = counted_loop(Some(7)); - // The store (and the heap handle it goes through) are in the module. - assert!(crumbs.dxil.len() > plain.dxil.len()); - assert!(crumbs.wave_ops && !plain.wave_ops); - // The first dword past the console's (one root constant: s0). - let heap_index: Vec<_> = crumbs - .user_data - .iter() - .filter(|u| u.root == crate::emit::BREADCRUMB_ROOT) - .collect(); - assert_eq!(heap_index.len(), 1); - assert_eq!(heap_index[0].index, 1); - // Everything else is unchanged. - assert_eq!( - crumbs.user_data.len(), - plain.user_data.len() + 1, - "{:?}", - crumbs.user_data - ); -} - -/// Root parameter `slot` in user SGPRs from `user_data` on. -fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { - RootParam { - root, - table_offset_dwords: 0, - sgprs: if root == RootType::Descriptor { 2 } else { 1 }, - base_register: 0, - user_data, - slot, - } -} - -#[test] -fn buffer_cache_invalidations_lower_as_no_ops() { - // MUBUF opcode 0x071/0x072 with no data operand: the title asks the - // host to invalidate its cached view of a buffer. - assert!( - lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), - "buffer_gl0_inv" - ); - assert!( - lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), - "buffer_gl1_inv" - ); -} - -#[test] -fn a_scalar_carry_chain_reaches_the_select() { - // The high dword of a 64-bit add or subtract, then a select on the - // carry (borrow) the high half leaves in SCC, and a branch on it - // (only code with an effect needs its operands). - let add = [ - 0xBE80_03C1, // s_mov_b32 s0, -1 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0x8000_8100, // s_add_u32 s0, s0, 1 - 0x8201_8001, // s_addc_u32 s1, s1, 0 - 0x8502_0001, // s_cselect_b32 s2, s1, s0 - 0xBF07_8002, // s_cmp_lg_u32 s2, 0 - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE83_0380, // s_mov_b32 s3, 0 - S_ENDPGM, - ]; - let sub = [ - 0xBE80_0380, // s_mov_b32 s0, 0 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0x8080_8100, // s_sub_u32 s0, s0, 1 - 0x8281_8001, // s_subb_u32 s1, s1, 0 - 0x8502_0001, // s_cselect_b32 s2, s1, s0 - 0xBF07_8002, // s_cmp_lg_u32 s2, 0 - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE83_0380, // s_mov_b32 s3, 0 - S_ENDPGM, - ]; - - for words in [add, sub] { - lowers(&words, 0).unwrap(); - } -} - -#[test] -fn v_cndmask_accepts_uniform_and_constant_masks() { - // Uniform select (`s_cselect_b32`) and inline constant masks in `v_cndmask_b32` - // (resolved in `Structured::other` or directly as constants). - let words = [ - 0xBF06_8000u32, // s_cmp_eq_u32 s0, 0 - 0x8500_80C1, // s_cselect_b32 s0, -1, 0 - 0xD501_0001, - 0x0001_0080, // v_cndmask_b32 v1, 0, 1, s0 - 0xD501_0002, - 0x0201_02C1, // v_cndmask_b32 v2, 1, v1, -1 - 0xD834_0000, - 0x0000_0200, // ds_write_b32 v0, v2 - S_ENDPGM, - ]; - lowers(&words, 0x8001).unwrap(); -} - -fn perm_features(selector: u32) -> u64 { - // Synthetic compute shader: - // v0 is the thread ID and can supply a dynamic selector. - // Store the result in LDS to keep the permutation live. - let words = [ - 0x7E02_02FFu32, - 0x817F_34AB, - 0x7E04_02FF, - 0xFE01_56CD, - 0xD744_0003, - 257 | (258 << 9) | (selector << 18), - 0x3408_0082, - 0xD834_0000, - 0x0000_0304, - S_ENDPGM, - ]; - - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 1 << 15, - threads: [64, 1, 1], - }), - code, - }; - - let p = ir::build(&native.code, false, 256).unwrap(); - - assert!( - p.blocks - .iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "v_perm_b32") - ); - - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - - let io = io::raise(&p, &native).unwrap(); - - let emitted = lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - crumbs: None, - emulate_mesh: false, - }) - .unwrap(); - - let container = crate::Container::parse(&emitted.dxil).unwrap(); - - let features = container.part(crate::FourCC::SFI0).unwrap(); - - u64::from_le_bytes(features.data.try_into().unwrap()) -} - -#[test] -fn perm_constant_selector_needs_no_int64() { - assert_eq!(perm_features(128) & 0x8000, 0); -} - -#[test] -fn perm_dynamic_selector_needs_no_int64() { - assert_eq!( - perm_features(256) & 0x8000, - 0, - "dynamic v_perm_b32 must not require INT64" - ); -} - -#[test] -fn scalar_loads_through_a_heap_buffer_that_vector_accesses_use_read_a_buffer_view() { - // A descriptor from the resource heap (s0) at an index from a root - // constant (s1), read by a scalar buffer load, then used by nothing - // else, by a vector buffer load, or by a vector buffer store. A slot - // that vector accesses use is a buffer view (an SRV if they only - // read it, a UAV if one writes it), so the scalar load must not read - // it through a constant buffer handle (a descriptor of the wrong - // type). With no other use, nothing says it isn't a CBV. - #[derive(Clone, Copy)] - enum Also { - Nothing, - Load, - Store, - } - let program = |also: Also| { - let mut words = vec![ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0x8F06_8501, // s_lshl_b32 s6, s1, 5 - 0xF408_0202, - 0x0C00_0000, // s_load_dwordx4 s[8:11], s[4:5], s6 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xF420_0304, - 0xFA00_0000, // s_buffer_load_dword s12, s[8:11], 0x0 - 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) - 0x7E02_020C, // v_mov_b32 v1, s12 - ]; - match also { - Also::Nothing => {} - Also::Load => words.extend([ - 0xE030_1000, - 0x8002_0200, // buffer_load_dword v2, v0, s[8:11], 0 offen - 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) - 0x4A02_0302, // v_add_nc_u32 v1, v2, v1 - ]), - Also::Store => words.extend([ - 0xE070_1000, - 0x8002_0100, // buffer_store_dword v1, v0, s[8:11], 0 offen - ]), - } - words.extend([ - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]); - words - }; - let layout = || { - vec![ - root(RootType::ResourceHeap, 0, 0), - root(RootType::Constants, 1, 1), - ] - }; - let cbuffers = |also| { - lower_with(&program(also), layout(), vec![]) - .unwrap() - .cbuffer_handles - }; - assert_eq!(cbuffers(Also::Nothing), 1, "no other use: a CBV"); - assert_eq!(cbuffers(Also::Load), 0, "buffer_load: an SRV"); - assert_eq!(cbuffers(Also::Store), 0, "buffer_store: a UAV"); -} - -#[test] -fn a_descriptor_selected_by_scc_picks_its_heap_index() { - // Two buffer descriptors loaded from the table at s0, one picked by - // a root constant (s1) with s_cselect_b64 per half, and loaded - // through by index and stored to LDS so the load is needed. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xF408_0302, - 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 - 0xBF06_8001, // s_cmp_eq_u32 s1, 0 - 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] - 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] - 0xE030_2000, - 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - // Both are structured buffers of dwords in the table's range. - let used = || { - vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }] - }; - lower_with(&words, layout(), used()).unwrap(); -} - -#[test] -fn image_atomic_64_bit_lowers_with_int64_feature() { - // Table address at s0 loaded into s[2:3], s_load_dwordx8 s[0:7], s[2:3], null - // then MIMG image_atomic_add v[0:1], v[2:3], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D - let words = [ - 0xBE82_0300, // s_mov_b32 s2, s0 - 0xBE83_0380, // s_mov_b32 s3, 0 - 0xF40C_0001, - 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null - 0xF044_0308, - 0x0000_0002, // image_atomic_add v[0:1], v[2:3], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D - S_ENDPGM, - ]; - let layout = || vec![root(RootType::Table, 0, 0)]; - let used = || { - vec![UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 8, - user_data: 0, - slot: 0, - }] - }; - let l = lower_with(&words, layout(), used()).unwrap(); - #[cfg(windows)] - if let Ok(mut v) = crate::emit::validator::Validator::load( - crate::emit::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut l.dxil.clone()).unwrap(); - } - let container = crate::Container::parse(&l.dxil).unwrap(); - let features = container.part(crate::FourCC::SFI0).unwrap(); - let sfi0 = u64::from_le_bytes(features.data.try_into().unwrap()); - assert_ne!( - sfi0 & 0x8000, - 0, - "64-bit image atomic must declare INT64 feature" - ); - assert_ne!( - sfi0 & 0x40_0000, - 0, - "64-bit image atomic must declare ATOMIC_INT64_ON_TYPED_RESOURCE" - ); - assert_ne!( - sfi0 & 0x1000_0000, - 0, - "64-bit image atomic from descriptor heap must declare ATOMIC_INT64_ON_HEAP_RESOURCE" - ); -} - -#[test] -fn image_atomic_32_and_64_handles_do_not_collide_in_cache() { - // Table address at s0 loaded into s[2:3], s_load_dwordx8 s[0:7], s[2:3], null - // then 32-bit image_atomic_add v0, v2, s[0:7] dmask:0x1 - // then 64-bit image_atomic_add v[0:1], v[2:3], s[0:7] dmask:0x3 - let words = [ - 0xBE82_0300, // s_mov_b32 s2, s0 - 0xBE83_0380, // s_mov_b32 s3, 0 - 0xF40C_0001, - 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null - 0xF044_0108, - 0x0000_0002, // image_atomic_add v0, v2, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D - 0xF044_0308, - 0x0000_0002, // image_atomic_add v[0:1], v[2:3], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D - S_ENDPGM, - ]; - let layout = || vec![root(RootType::Table, 0, 0)]; - let used = || { - vec![UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 8, - user_data: 0, - slot: 0, - }] - }; - let _l = lower_with(&words, layout(), used()).unwrap(); - #[cfg(windows)] - if let Ok(mut v) = crate::emit::validator::Validator::load( - crate::emit::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut _l.dxil.clone()).unwrap(); - } -} - -#[test] -fn a_descriptor_read_only_as_data_takes_the_kind_of_its_entrys_use() { - // The table entry at s0 loaded twice: the second load's descriptor - // reads a structured buffer, the first's record count (dword 2) is - // only read as a number, as the console compiler does for a size. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xF408_0302, - 0xFA00_0000, // s_load_dwordx4 s[12:15], s[4:5], null - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xE030_2000, - 0x8003_0100, // buffer_load_dword v1, v0, s[12:15], 0 idxen - 0x7E04_020A, // v_mov_b32 v2, s10 - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - 0xD834_0000, - 0x0000_0200, // ds_write_b32 v0, v2 - S_ENDPGM, - ]; - let layout = vec![root(RootType::Table, 0, 0)]; - let used = vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }]; - lower_with(&words, layout, used).unwrap(); -} - -/// Tables of 2D textures at s0 and samplers at s1. -fn texture_tables() -> (Vec, Vec) { - let range = |kind, user_data, slot| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, - user_data, - slot, - }; - ( - vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], - vec![ - range(ResourceType::Srv, 0, 0), - range(ResourceType::Sampler, 1, 1), - ], - ) -} - -#[test] -fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { - use crate::resource::tests::{ - WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, - }; - for (words, wave64) in [ - (WATERFALL_FETCHED_WAVE32, false), - (WATERFALL_FETCHED_WAVE64, true), - (WATERFALL_PICKED_WAVE32, false), - ] { - let (layout, used) = texture_tables(); - let l = lower_wave(words, layout, used, wave64).unwrap(); - // The loop's reads of the first lane became each lane's own - // dwords: no wave operation is left. - assert_eq!(l.nonuniform_handles, 1); - assert!(!l.wave_ops); - } -} - -/// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. -pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { - let (layout, mut used) = texture_tables(); - used.push(UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 16, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 0, - slot: 0, - }); - (layout, used) -} - -#[test] -fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { - use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; - for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { - let (layout, used) = texture_and_uav_tables(); - let l = lower_wave(words, layout, used, false).unwrap(); - // One image handle, from the join's per-lane heap index. - assert_eq!(l.nonuniform_handles, 1); - assert!(!l.wave_ops); - } -} - -#[test] -fn 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); - validate_dxil(&l.dxil); -} - -#[test] -fn scalar_bit_tests_lower() { - // Each tests one bit of a constant into SCC and branches on it (only - // code with an effect needs its operands). - let tail = [ - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE84_0380, // s_mov_b32 s4, 0 - S_ENDPGM, - ]; - let bit_tests: [&[u32]; 4] = [ - &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 - &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 - &[ - 0xBE80_0387, // s_mov_b32 s0, 7 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 - ], - &[ - 0xBE80_0387, // s_mov_b32 s0, 7 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 - ], - ]; - for head in bit_tests { - let words: Vec = head.iter().chain(&tail).copied().collect(); - lowers(&words, 0).unwrap(); - } -} - -#[test] -#[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"] -fn a_missing_value_stays_missing_through_two_live_joins() { - let mut words = [ - 0xF490_0180, - 0, // s_memtime s[6:7] - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) - 0xBF85_0001, // skip the first overwrite - 0xBE86_0380, // s_mov_b32 s6, 0 - 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) - 0xBF85_0001, // skip the second overwrite - 0xBE86_0381, // s_mov_b32 s6, 1 - 0xBF07_8006, // s_cmp_lg_u32 s6, 0 - 0xBF85_0001, // use the result to branch - 0xBE83_0380, - S_ENDPGM, - ]; - let group_ids_xy = 3 << 7; - // Compare to a direct read so future timestamp support works in both cases. - let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { - Ok(()) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - }; - let direct = [&words[..2], &words[8..]].concat(); - assert_eq!(refusal(&words), refusal(&direct)); - words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead - lowers(&words, group_ids_xy).expect("dead timestamp"); -} - -#[cfg(windows)] -fn validate_dxil(dxil: &[u8]) { - if let Ok(mut v) = super::super::validator::Validator::load( - super::super::validator::Validator::default_path().as_deref(), - ) { - let mut copy = dxil.to_vec(); - let ours = copy[4..20].to_vec(); - v.validate(&mut copy).expect("DXIL validation failed"); - assert_eq!(copy[4..20], ours[..], "container hash mismatch"); - } -} - -#[cfg(not(windows))] -fn validate_dxil(_dxil: &[u8]) {} - -#[test] -fn a_live_descriptor_word_stays_missing_through_two_joins() { - let mut words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 (table) - 0xBE85_0380, // s_mov_b32 s5, 0 - 0x7E00_0280, // v_mov_b32 v0, 0 - 0xBF06_8001, // s_cmp_eq_u32 s1, 0 (root constant) - 0xBF85_0002, // take the descriptor arm when SCC is set - 0xBE89_0391, // s_mov_b32 s9, 17 - 0xBF82_0006, // skip the descriptor arm - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 - 0xE030_2000, - 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - 0xBF85_0001, // if SCC is set, keep the descriptor word live - 0xBE89_039D, // s_mov_b32 s9, 29 - 0x7E04_0209, // v_mov_b32 v2, s9 - 0xD834_0000, - 0x0000_0200, // ds_write_b32 v0, v2 - S_ENDPGM, - ]; - let run = |words: &[u32]| { - let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - let used = vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }]; - lower_wave(words, layout, used, false) - }; - let reason = |words: &[u32]| match run(words) { - Ok(_) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - }; - let through_two_joins = reason(&words); - assert_eq!( - through_two_joins, - Some("a buffer descriptor's stride or high address read as data") - ); - words[13] = 0xBF82_0001; // skip the overwrite unconditionally: one join - assert_eq!(through_two_joins, reason(&words)); - - // Correlated overwrite: when SCC is set, always overwrite s9 = 29 before reading it. - words[13] = 0xBF84_0001; // s_cbranch_scc0 +1 (skip overwrite only when SCC is clear) - let lowered = run(&words).expect("overwritten descriptor word must lower"); - validate_dxil(&lowered.dxil); -} - -#[test] -fn unknown_stride_load_stays_missing_when_live_and_lowers_when_overwritten() { - let mut words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 (table) - 0xBE85_0380, // s_mov_b32 s5, 0 - 0x7E00_0280, // v_mov_b32 v0, 0 - 0xBF06_8001, // s_cmp_eq_u32 s1, 0 (root constant) - 0xBF85_0002, // take the unknown-stride load arm when SCC is set - 0x7E02_0291, // v_mov_b32 v1, 17 - 0xBF82_0004, // skip the load arm - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 - 0xE030_2000, - 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen (unknown stride -> Missing) - 0xBF85_0001, // if SCC is set, keep the missing load live - 0x7E02_029D, // v_mov_b32 v1, 29 - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let run = |words: &[u32]| { - let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - let used = vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, // unknown stride - dwords: 4, - user_data: 0, - slot: 0, - }]; - lower_wave(words, layout, used, false) - }; - let reason = |words: &[u32]| match run(words) { - Ok(_) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - }; - let two_joins = reason(&words); - assert_eq!(two_joins, Some("a structured buffer of unknown stride")); - words[11] = 0xBF82_0001; // s_branch +1: one join - assert_eq!(two_joins, reason(&words)); - - // Correlated overwrite: when SCC is set, always overwrite v1 = 29. - words[11] = 0xBF84_0001; // s_cbranch_scc0 +1 - let lowered = run(&words).expect("overwritten unknown-stride load must lower"); - validate_dxil(&lowered.dxil); -} - -#[test] -fn first_half_of_interpolation_stays_missing_when_live_and_lowers_when_overwritten() { - let mut words = [ - 0xC808_0000u32, // v_interp_p1_f32 v2, v0, attr0.x (Missing) - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 - 0xBF84_0001, // s_cbranch_scc0 +1 (skip p2 when s0 != 0) - 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x - 0xBF85_0001, // s_cbranch_scc1 +1 (skip overwrite when s0 == 0) - 0x7E04_0280, // v_mov_b32 v2, 0 - 0xF800_180F, - 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm - S_ENDPGM, - ]; - let run = |words: &[u32]| { - let native = NativeProgram { - stage: HwStage::Ps, - wave64: false, - vgprs: 4, - layout: vec![root(RootType::Constants, 0, 0)], - used: vec![], - io: StageIo::Ps { - rsrc2: 0, - inputs: vec![crate::native::PsInput { - usage: crate::native::Usage::Generic, - row: 0, - mask: 0b1111, - attr: 0, - flat: false, - fp16: false, - pack2: false, - row2: 0, - }], - input_addr: 1 << 1, // PERSP_CENTER - db_shader_control: 0, - patches: vec![], - }, - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let p = ir::build(&native.code, false, 4).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 outputs = vec![super::SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 0, - half: false, - }]; - let inputs = vec![super::SigElement { - name: "TEXCOORD".into(), - index: 0, - kind: 0, - comp: 9, - interp: 2, - row: Some(0), - col: 0, - cols: 4, - usage: 0, - half: false, - }]; - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs, - outputs, - prims: vec![], - mesh_stride: 0, - crumbs: None, - emulate_mesh: false, - }) - }; - // Overwritten on the s0 != 0 branch: p1 never reaches exp. - let lowered = run(&words).expect("overwritten interp half must lower"); - validate_dxil(&lowered.dxil); - - // Flip word 4 to s_cbranch_scc0 +1: when s0 != 0, p1 reaches exp live. - words[4] = 0xBF84_0001; - let Err(crate::ShaderError::Unsupported { what, .. }) = run(&words) else { - panic!("live p1 must refuse"); - }; - assert_eq!(what, "the first half of an interpolation"); - - // Unconditional skip (1 join): also refuses identically. - words[4] = 0xBF82_0001; - let Err(crate::ShaderError::Unsupported { what, .. }) = run(&words) else { - panic!("1-join live p1 must refuse"); - }; - assert_eq!(what, "the first half of an interpolation"); -} - -#[test] -fn guarded_write_and_exec_mask_phi_lower_soundly() { - // 1. EXEC phi fed by a scalar SGPR in one branch, then read via s_bcnt1_i32_b32. - let exec_phi_words = [ - 0xBE84_03BF, // s_mov_b32 s4, 0x3F - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 - 0xBF84_0001, // s_cbranch_scc0 +1 - 0xBEFE_0304, // s_mov_b32 exec_lo, s4 - 0xBE82_0F7E, // s_bcnt1_i32_b32 s2, exec_lo - 0x7E00_0202, // v_mov_b32 v0, s2 - 0xD834_0000, - 0x0000_0000, // ds_write_b32 v0, v0 - S_ENDPGM, - ]; - let lowered = lower_wave( - &exec_phi_words, - vec![root(RootType::Constants, 0, 0)], - vec![], - false, - ) - .expect("EXEC phi read via mask_ok must lower"); - validate_dxil(&lowered.dxil); - - // 2. Guarded write (`write_placed`) preserving `17` on `!guard` lanes where `guard` - // lanes held an unknown-stride load (and overwriting `guard` lanes with `29`). - let guarded_words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 (table) - 0xBE85_0380, // s_mov_b32 s5, 0 - 0x7E00_0280, // v_mov_b32 v0, 0 - 0x7E02_0291, // v_mov_b32 v1, 17 - 0x7D84_0080, // v_cmp_eq_u32 vcc_lo, 0, v0 - 0xBE86_3C6A, // s_and_saveexec_b32 s6, vcc_lo - 0xBF88_0004, // s_cbranch_execz +4 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 - 0xE030_2000, - 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen (unknown stride) - 0xBEFE_0306, // s_mov_b32 exec_lo, s6 - 0xBE86_3C6A, // s_and_saveexec_b32 s6, vcc_lo - 0x7E02_029D, // v_mov_b32 v1, 29 (guarded by v0 == 0, keeps v1 = 17 on v0 != 0) - 0xBEFE_0306, // s_mov_b32 exec_lo, s6 - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - // Lowers on fxceless through their `slot_stride` upload table (the - // deferred strides port); until it lands, the unknown stride is - // still refused by name. - let e = match lower_wave( - &guarded_words, - vec![root(RootType::Table, 0, 0)], - vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 0, - slot: 0, - }], - false, - ) { - Ok(_) => panic!("the unknown-stride load lowered without slot strides"), - Err(e) => e, - }; - assert!( - e.to_string() - .contains("a structured buffer of unknown stride"), - "{e}" - ); -} - -#[test] -fn loop_missing_value_refuses_on_back_edge_and_lowers_when_infeasible() { - // Loop header (word 4): s2 starts at 17, v7 = 0. Inside loop: if s0 == 0, s_memtime -> s2. - // Latch uses VCC so loop-invariant scc (s0 == 0) survives across iterations. - // After loop: if s0 == 0, overwrite s2 = 29, else read P_s2. - let mut words = [ - 0x7E00_0280, // 0: v_mov_b32 v0, 0 - 0xBE82_0391, // 1: s_mov_b32 s2, 17 - 0x7E0E_0280, // 2: v_mov_b32 v7, 0 - 0xBF06_8000, // 3: s_cmp_eq_u32 s0, 0 (loop-invariant, preserved in SCC) - // loop header (word 4): - 0xBF84_0003, // 4: s_cbranch_scc0 +3 (skip s_memtime when s0 != 0) - 0xF490_0180, - 0, // 5-6: s_memtime s[6:7] - 0xBE82_0306, // 7: s_mov_b32 s2, s6 - // latch (word 8): - 0x4A0E_0E81, // 8: v_add_nc_u32 v7, 1, v7 - 0x7D88_0E82, // 9: v_cmp_gt_u32 vcc_lo, 2, v7 - 0xBF87_FFF9, // 10: s_cbranch_vccnz -7 (back to word 4) - // after loop (word 11): - 0xBF84_0001, // 11: s_cbranch_scc0 +1 (skip overwrite when s0 != 0) - 0xBE82_039D, // 12: s_mov_b32 s2, 29 - 0x7E02_0202, // 13: v_mov_b32 v1, s2 - 0xD834_0000, - 0x0000_0100, // 14-15: ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let run = - |words: &[u32]| lower_wave(words, vec![root(RootType::Constants, 0, 0)], vec![], false); - let lowered = run(&words).expect("loop-invariant infeasible missing edge must lower"); - validate_dxil(&lowered.dxil); - - // Flip word 11 to s_cbranch_scc1 +1: s_memtime from back-edge reaches ds_write when s0 == 0. - words[11] = 0xBF85_0001; - let Err(crate::ShaderError::Unsupported { what, .. }) = run(&words) else { - panic!("live loop back-edge missing value must refuse"); - }; - assert_eq!(what, "a timestamp read as data"); -} - -#[test] -fn old_register_missing_values_and_cached_floats_stay_refused() { - let srv_used = || { - vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 0, - slot: 0, - }] - }; - let expect_unsupported = |res: Result, want: &str| match res { - Ok(_) => panic!("expected refusal `{want}`, but lowered"), - Err(crate::ShaderError::Unsupported { what, .. }) => assert_eq!(what, want), - Err(error) => panic!("{error}"), - }; - - // 1a. Direct Val::Missing on `old` surviving into `!guard` of `write_placed`. - let direct_old_guard = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0x7E00_0280, // v_mov_b32 v0, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 - 0xE030_2000, - 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen (unknown stride) - 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 (v0 < 16) - 0xBE86_3C6A, // s_and_saveexec_b32 s6, vcc_lo - 0x7E02_029D, // v_mov_b32 v1, 29 (v0 >= 16 keeps old unknown-stride v1) - 0xBEFE_0306, // s_mov_b32 exec_lo, s6 - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - expect_unsupported( - lower_wave( - &direct_old_guard, - vec![root(RootType::Table, 0, 0)], - srv_used(), - false, - ), - "a structured buffer of unknown stride", - ); - - // 1b. Phi Val::Missing on `old` surviving into `!guard` of `write_placed`. - let phi_old_guard = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0x7E00_0280, // v_mov_b32 v0, 0 - 0x7E02_0291, // v_mov_b32 v1, 17 - 0x7D84_0080, // v_cmp_eq_u32 vcc_lo, 0, v0 (v0 == 0) - 0xBE86_3C6A, // s_and_saveexec_b32 s6, vcc_lo - 0xBF88_0004, // s_cbranch_execz +4 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 - 0xE030_2000, - 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen - 0xBEFE_0306, // s_mov_b32 exec_lo, s6 - 0x7D8A_0080, // v_cmp_ne_u32 vcc_lo, 0, v0 (v0 != 0 -> !guard keeps v0 == 0!) - 0xBE86_3C6A, // s_and_saveexec_b32 s6, vcc_lo - 0x7E02_029D, // v_mov_b32 v1, 29 - 0xBEFE_0306, // s_mov_b32 exec_lo, s6 - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - expect_unsupported( - lower_wave( - &phi_old_guard, - vec![root(RootType::Table, 0, 0)], - srv_used(), - false, - ), - "a structured buffer of unknown stride", - ); - - // 1c. Live Val::Missing on `old` kept by `write_16` (`keep == true`). - let write16_old = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0x7E00_0280, // v_mov_b32 v0, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 - 0xE030_2000, - 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen - 0x6402_00F2, // v_add_f16 v1, 1.0, v0 (keeps high 16 bits of v1) - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - expect_unsupported( - lower_wave( - &write16_old, - vec![root(RootType::Table, 0, 0)], - srv_used(), - false, - ), - "a structured buffer of unknown stride", - ); - - // 1d. Live Val::Missing on `old` kept by `place_bits` (SDWA `dst_unused: UNUSED_PRESERVE`). - let sdwa_old = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0x7E00_0280, // v_mov_b32 v0, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 - 0xE030_2000, - 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen - 0x7E02_02F9, - 0x0006_1400, // v_mov_b32_sdwa v1, v0 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - expect_unsupported( - lower_wave( - &sdwa_old, - vec![root(RootType::Table, 0, 0)], - srv_used(), - false, - ), - "a structured buffer of unknown stride", - ); - - // 1e. Direct Val::Missing on `outside` surviving `!guard` of `ds_add_rtn_u32`. - let ds_rtn_outside = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0x7E00_0280, // v_mov_b32 v0, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 - 0xE030_2000, - 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen - 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 (v0 < 16) - 0xBE86_3C6A, // s_and_saveexec_b32 s6, vcc_lo - 0xD880_0000, - 0x0100_0000, // ds_add_rtn_u32 v1, v0, v0 (v0 >= 16 keeps outside = unknown-stride v1) - 0xBEFE_0306, // s_mov_b32 exec_lo, s6 - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - expect_unsupported( - lower_wave( - &ds_rtn_outside, - vec![root(RootType::Table, 0, 0)], - srv_used(), - false, - ), - "a structured buffer of unknown stride", - ); - - // 2. Live missing phi flowing through chained float ops (`self.floats` cache hit) to `ds_write`. - let chained_float_phi = [ - 0x7E00_0280, // v_mov_b32 v0, 0 - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 - 0xBF85_0002, // take s_memtime arm when s0 == 0 - 0xBE82_0391, // s_mov_b32 s2, 17 - 0xBF82_0003, // skip s_memtime - 0xF490_0180, - 0, // s_memtime s[6:7] - 0xBE82_0306, // s_mov_b32 s2, s6 - 0x0604_0002, // v_add_f32 v2, s2, v0 (inserts v2 into self.floats) - 0x0A06_04F4, // v_mul_f32 v3, 2.0, v2 (hits self.floats[&v2], inserts v3 into self.floats) - 0xD834_0000, - 0x0000_0300, // ds_write_b32 v0, v3 - S_ENDPGM, - ]; - expect_unsupported( - lower_wave( - &chained_float_phi, - vec![root(RootType::Constants, 0, 0)], - vec![], - false, - ), - "a timestamp read as data", - ); -} - -/// The names `words` decode to, to check hand-written encodings. -fn names(words: &[u32]) -> Vec<&'static str> { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let p = ir::build(&code, false, 256).unwrap(); - p.blocks - .iter() - .flat_map(|b| b.insts.iter().map(|i| i.name())) - .collect() -} - -/// The reason a program stops, or `None` if it translates. -fn refusal(r: Result) -> Option<&'static str> { - match r { - Ok(_) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - } -} - -/// A descriptor table at s0 whose first entry is a buffer of `kind` -/// and `stride`. -fn buffer_table(kind: ResourceType, stride: u32) -> (Vec, Vec) { - let used = UsedResource { - kind, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride, - dwords: 4, - user_data: 0, - slot: 0, - }; - (vec![root(RootType::Table, 0, 0)], vec![used]) -} - -#[test] -fn scalar_loaded_buffer_descriptors_read_as_data_name_the_dword_and_kind() { - // A buffer descriptor that scalar buffer loads read through, one - // of whose dwords is also stored as a number. - let program = |word: u32| { - vec![ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xF420_0304, - 0xFA00_0000, // s_buffer_load_dword s12, s[8:11], null - word, // v_mov_b32 v1, s10 (dword 2) or s8 (dword 0) - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ] - }; - let (dword2, dword0) = (0x7E02_020A, 0x7E02_0208); - assert_eq!( - names(&program(dword2)), - [ - "s_mov_b32", - "s_mov_b32", - "s_load_dwordx4", - "s_buffer_load_dword", - "v_mov_b32", - "ds_write_b32", - "s_endpgm" - ] - ); - let cases = [ - ( - ResourceType::Srv, - 0, - "a scalar-loaded raw buffer's record count read as data", - ), - ( - ResourceType::Srv, - 16, - "a scalar-loaded structured buffer's record count read as data", - ), - ( - ResourceType::Cbv, - 0, - "a scalar-loaded constant buffer's record count read as data", - ), - ( - ResourceType::Uav, - 0, - "a scalar-loaded buffer's record count read as data", - ), - ]; - for (kind, stride, want) in cases { - let (layout, used) = buffer_table(kind, stride); - let got = refusal(lower_with(&program(dword2), layout.clone(), used.clone())); - assert_eq!(got, Some(want), "{kind:?}, stride {stride}"); - assert_eq!( - refusal(lower_with(&program(dword0), layout, used)), - Some("a scalar-loaded buffer's address or format read as data"), - "{kind:?}, stride {stride}" - ); - } - // The same descriptor also read by a vector load later: the record - // count has a host value once that use decides the view, so the - // scalar load's dwords lower too. - let mut words = program(dword2); - words.splice( - 6..6, - [ - 0xE030_0000, - 0x8002_0100, // buffer_load_dword v1, off, s[8:11], 0 - ], - ); - assert!(names(&words).contains(&"buffer_load_dword")); - let (layout, used) = buffer_table(ResourceType::Srv, 0); - assert!(lower_with(&words, layout, used).is_ok()); -} - -#[test] -fn scalar_memory_that_is_no_descriptor_names_what_it_reads() { - // Each value stored to LDS, so that the program needs it. - let program = |op: [u32; 2], sgpr: u32| { - vec![ - op[0], - op[1], - 0x7E02_0200 | sgpr, // v_mov_b32 v1, s - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ] - }; - let cases = [ - ([0xF490_0180, 0], "s_memtime", "a timestamp read as data"), - ( - [0xF494_0180, 0], - "s_memrealtime", - "a timestamp read as data", - ), - ( - [0xF4A8_0180, 0], - "s_get_waveid_in_workgroup", - "a wave's index in its group read as data", - ), - ]; - for (op, name, want) in cases { - let words = program(op, 6); - assert_eq!(names(&words)[0], name); - assert_eq!( - refusal(lower_with(&words, vec![], vec![])), - Some(want), - "{name}" - ); - } - // A load through a root view's address (s[0:1]) reads that - // buffer's memory (`root_view_smem` lowers it); one from a table - // with no use reads a descriptor. - let root_view = program([0xF400_0180, 0xFA00_0000], 6); // s_load_dword s6, s[0:1], null - assert_eq!(names(&root_view)[0], "s_load_dword"); - lower_with(&root_view, vec![root(RootType::Descriptor, 0, 0)], vec![]) - .expect("a root view's memory read by scalar loads lowers"); - // A table load with no resource use reads the bound descriptor - // words (ray tracing reads them for GPU addresses). - let mut table = vec![0xBE84_0300, 0xBE85_0380]; // s_mov_b32 s4, s0; s_mov_b32 s5, 0 - table.extend(program([0xF400_0182, 0xFA00_0000], 6)); // s_load_dword s6, s[4:5], null - assert_eq!(names(&table)[2], "s_load_dword"); - lower_with(&table, vec![root(RootType::Table, 0, 0)], vec![]) - .expect("a descriptor read only as data gets the bound words"); -} - -#[test] -fn descriptor_dwords_read_as_data_name_what_they_hold() { - // An image descriptor that a sample uses and a buffer descriptor - // that a load uses, one dword of each stored as a number. Dwords - // the translation rebuilds from the host view translate. - let image = |sgpr: u32| { - vec![ - 0xBE82_0300, // s_mov_b32 s2, s0 - 0xBE83_0380, // s_mov_b32 s3, 0 - 0xF40C_0301, - 0xFA00_0000, // s_load_dwordx8 s[12:19], s[2:3], null - 0xBE84_0301, // s_mov_b32 s4, s1 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0x7E04_0280, // v_mov_b32 v2, 0 - 0x7E06_0280, // v_mov_b32 v3, 0 - 0xF09C_0F08, - 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:2D - 0x7E02_0200 | sgpr, // v_mov_b32 v1, s - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ] - }; - assert_eq!(names(&image(12))[8], "image_sample_lz"); - for (dword, want) in [ - (0, Some("an image descriptor's address read as data")), - (2, None), - ( - 5, - Some("an image descriptor's array pitch or mip limits read as data"), - ), - ( - 6, - Some("an image descriptor's compression fields read as data"), - ), - ( - 7, - Some("an image descriptor's metadata address read as data"), - ), - ] { - let (layout, used) = texture_tables(); - let got = refusal(lower_with(&image(12 + dword), layout, used)); - assert_eq!(got, want, "image dword {dword}"); - } - let buffer = |sgpr: u32| { - vec![ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xE030_0000, - 0x8002_0100, // buffer_load_dword v1, off, s[8:11], 0 - 0x7E02_0200 | sgpr, // v_mov_b32 v1, s - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ] - }; - assert_eq!(names(&buffer(8))[3], "buffer_load_dword"); - for (dword, want) in [ - (0, Some("a buffer descriptor's address read as data")), - ( - 1, - Some("a buffer descriptor's stride or high address read as data"), - ), - (2, None), - ( - 3, - Some("a buffer descriptor's format or swizzle read as data"), - ), - ] { - let (layout, used) = buffer_table(ResourceType::Srv, 0); - let got = refusal(lower_with(&buffer(8 + dword), layout, used)); - assert_eq!(got, want, "buffer dword {dword}"); - } -} - -#[test] -fn buffer_formats_by_number() { - // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, - // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. - assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); - assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); - assert_eq!( - buffer_format(50), - Some((&[10, 10, 10, 2][..], Numeric::Unorm)) - ); - assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); - assert_eq!( - buffer_format(77), - Some((&[32, 32, 32, 32][..], Numeric::Float)) - ); - // Invalid, past the table. - assert_eq!(buffer_format(0), None); - assert_eq!(buffer_format(78), None); -} - -#[test] -fn packed_buffer_formats_by_number() { - // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, - // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT - // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. - assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); - assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); - assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); - assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); - assert_eq!( - buffer_format(44), - Some((&[2, 10, 10, 10][..], Numeric::Unorm)) - ); - assert_eq!( - buffer_format(45), - Some((&[2, 10, 10, 10][..], Numeric::Snorm)) - ); - assert_eq!( - buffer_format(46), - Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) - ); - assert_eq!( - buffer_format(47), - Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) - ); - assert_eq!( - buffer_format(48), - Some((&[2, 10, 10, 10][..], Numeric::Uint)) - ); - assert_eq!( - buffer_format(49), - Some((&[2, 10, 10, 10][..], Numeric::Sint)) - ); -} - -/// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as -/// `legacyF16ToF32` widens it. -fn half(h: u32) -> f32 { - let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); - let v = match e { - 0 => m as f32 * 2f32.powi(-24), - 31 if m == 0 => f32::INFINITY, - 31 => f32::NAN, - _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), - }; - if s == 1 { -v } else { v } -} - -#[test] -fn small_floats_widen_as_halves() { - // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a - // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. - let f11 = |x: u32| half(x << half_shift(11)); - let f10 = |x: u32| half(x << half_shift(10)); - assert_eq!(f11(0), 0.0); - assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal - assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal - assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal - assert_eq!(f11(0x3C0), 1.0); - assert_eq!(f11(0x3E0), 1.5); - assert_eq!(f11(0x7BF), 65024.0); // largest - assert_eq!(f11(0x7C0), f32::INFINITY); - assert!(f11(0x7C1).is_nan()); - assert_eq!(f10(0x001), 2f32.powi(-19)); - assert_eq!(f10(0x020), 2f32.powi(-14)); - assert_eq!(f10(0x1E0), 1.0); - assert_eq!(f10(0x3DF), 64512.0); - assert_eq!(f10(0x3E0), f32::INFINITY); - assert!(f10(0x3FF).is_nan()); - // A 16-bit float is a half already, sign included. - assert_eq!(half(0xBC00 << half_shift(16)), -1.0); -} - -#[test] -fn constant_64_bit_compares_lower_without_int64() { - for (vopc, branch) in [ - (0x7DC0_0080u32, 0xBF86_0001u32), // v_cmp_f_u64 vcc, ...; s_cbranch_vccnz - (0x7D4E_0080, 0xBF86_0001), // v_cmp_t_i64 vcc, ...; s_cbranch_vccnz - (0x7DE0_0080, 0xBF89_0001), // v_cmpx_f_u64 exec, ...; s_cbranch_execnz - (0x7D6E_0080, 0xBF89_0001), // v_cmpx_t_i64 exec, ...; s_cbranch_execnz - ] { - let words = [ - 0x7E00_0280u32, // v_mov_b32 v0, 0 - 0x7E02_0280, // v_mov_b32 v1, 0 - vopc, - branch, - 0xBE80_0380, // s_mov_b32 s0, 0 - S_ENDPGM, - ]; - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 2, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 0, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 2).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 emitted = lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - crumbs: None, - emulate_mesh: false, - }) - .unwrap(); - let sfi0 = crate::dxbc::Container::parse(&emitted.dxil) - .unwrap() - .part(crate::dxbc::FourCC::SFI0) - .unwrap() - .data; - let features = u64::from_le_bytes(sfi0.try_into().unwrap()); - assert_eq!(features & 0x8000, 0, "unexpected INT64 feature bit"); - } -} - -#[test] -fn permlane16_lowers() { - let words = [ - // v_permlanex16_b32 v2, v0, s0, s1 (VOP3 opcode 0x378) - 0xD778_0002, - (1 << 18) | 0x100, - S_ENDPGM, - ]; - lowers(&words, 0).expect("v_permlanex16_b32 should lower"); -} diff --git a/crates/victory-shader/src/emit/mesh_emu.rs b/crates/victory-shader/src/emit/mesh_emu.rs deleted file mode 100644 index fda59a2..0000000 --- a/crates/victory-shader/src/emit/mesh_emu.rs +++ /dev/null @@ -1,1365 +0,0 @@ -//! Mesh shader emulation (`cs_6_6` + generated unpack `vs_6_6`) for SM 6.6 -//! GPUs that lack hardware mesh shaders (`D3D12_MESH_SHADER_TIER_NOT_SUPPORTED`). -//! -//! An emulated mesh program (`MeshMode::Emulate`) compiles as a compute shader -//! (`cs_6_6`) with the console's `[numthreads(threads, 1, 1)]` and LDS, writing -//! packed primitive indices, per-vertex attributes (`OSG1`), and per-primitive -//! attributes (`PSG1`) into a fixed-stride per-group slice of a raw UAV buffer -//! at `u0` in [`MESH_EMU_SPACE`](super::shader::MESH_EMU_SPACE): -//! -//! ```text -//! group g (byte offset = g * group_bytes): -//! [0 .. index_bytes) max_primitives x u32 (v0 | v1<<10 | v2<<20 | cull<<31) -//! [index_bytes .. prim_offset_bytes) max_vertices x vertex_dwords x u32 -//! [prim_offset_bytes .. group_bytes) max_primitives x prim_dwords x u32 -//! ``` -//! -//! [`unpack_vertex_shader`] builds the matching `vs_6_6` that reads that raw -//! buffer at `t0` in [`MESH_EMU_SPACE`](super::shader::MESH_EMU_SPACE) by `SV_VertexID`, culls bit-31 primitives via quiet -//! `NaN` on `SV_Position`, and emits every vertex and per-primitive attribute in -//! the exact signature layout the title's pixel shader (`ps_6_6`) expects. - -use std::collections::BTreeMap; - -use super::bitcode::{Attr, Bin, Cast, Term, pred}; -use super::container::SigElement; -use super::shader::Shader; -use crate::ShaderError; -use crate::dxbc::{Container, FourCC, u32_at}; - -/// Sentinel `base_group` value in `b0` in [`MESH_EMU_SPACE`](super::shader::MESH_EMU_SPACE) telling an emulated mesh -/// compute shader that reads `SV_GroupID` to look up its per-record group ID -/// in the `slot_map` raw SRV (`t0` in the same space). -pub const INDIRECT_SLOT_MAP_FLAG: u32 = u32::MAX; - -/// Whether a console mesh shader (`HwStage::Ms`) translates to native `ms_6_6` -/// or to a compute + vertex emulation pair. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum MeshMode { - #[default] - Native, - Emulate, -} - -/// One vertex or per-primitive attribute stored in the emulated mesh buffer. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MeshOutput { - pub name: String, - pub index: u32, - pub kind: u8, - pub comp: u8, - pub interp: u8, - pub row: Option, - pub col: u8, - pub cols: u8, - /// Dword offset of channel 0 from the start of a vertex or primitive record. - pub dword_offset: u32, -} - -/// Memory layout and metadata emitted by an emulated mesh compute shader. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MeshEmu { - pub threads: u32, - pub max_vertices: u32, - pub max_primitives: u32, - pub vertex_dwords: u32, - pub prim_dwords: u32, - pub reads_group_id: bool, - pub vertex_outputs: Vec, - pub prim_outputs: Vec, -} - -impl MeshEmu { - /// Bytes reserved per group for packed primitive index words. - pub fn index_bytes(&self) -> u32 { - self.max_primitives * 4 - } - - /// Byte offset of vertex attribute records within one group slice. - pub fn vertex_offset_bytes(&self) -> u32 { - self.index_bytes() - } - - /// Stride in bytes of one vertex record. - pub fn vertex_stride_bytes(&self) -> u32 { - self.vertex_dwords * 4 - } - - /// Byte offset of per-primitive attribute records within one group slice. - pub fn prim_offset_bytes(&self) -> u32 { - self.index_bytes() + self.max_vertices * self.vertex_stride_bytes() - } - - /// Stride in bytes of one per-primitive record. - pub fn prim_stride_bytes(&self) -> u32 { - self.prim_dwords * 4 - } - - /// Total bytes occupied by one threadgroup in the intermediate buffer. - pub fn group_bytes(&self) -> u32 { - self.prim_offset_bytes() + self.max_primitives * self.prim_stride_bytes() - } -} - -#[derive(Clone, Copy)] -enum OutputSource { - Vertex { dword_offset: u32, avail_cols: u8 }, - Prim { dword_offset: u32, avail_cols: u8 }, - Zero, -} - -struct UnpackOutput { - sig: SigElement, - src: OutputSource, -} - -/// Generates a `vs_6_6` DXIL container that unpacks `emu`'s raw buffer (`t0, -/// space 2`) by `SV_VertexID` into the input signature expected by `ps_dxil` -/// (or rasterizer system values only for depth-only pipelines). -pub fn unpack_vertex_shader(emu: &MeshEmu, ps_dxil: Option<&[u8]>) -> Result, ShaderError> { - if emu.max_vertices == 0 || emu.max_primitives == 0 { - return Err(ShaderError::Unsupported { - offset: 0, - what: "an empty mesh shader output", - }); - } - - let plan = build_output_plan(emu, ps_dxil)?; - - let mut s = Shader::new(false); - s.inputs = vec![SigElement { - name: "SV_VertexID".into(), - index: 0, - kind: 1, - comp: 5, - interp: 0, - row: Some(0), - col: 0, - cols: 1, - usage: 1, - half: false, - }]; - s.outputs = plan.iter().map(|o| o.sig.clone()).collect(); - - let buf = s.emu_srv_handle(); - let e = s.entry; - let i32t = s.t.i32; - let undef_i32 = s.m.undef(i32t); - let vid = { - let zero = s.m.i32(0); - let z8 = s.m.i8(0); - s.op( - e, - "loadInput.i32", - Attr::ReadNone, - i32t, - 4, - &[zero, zero, z8, undef_i32], - ) - }; - - let k3 = s.m.i32(3); - let tri = s.m.bin(e, Bin::UDiv, vid, k3); - let corner = s.m.bin(e, Bin::URem, vid, k3); - let (group_idx, prim_idx) = if emu.max_primitives == 1 { - (tri, s.m.i32(0)) - } else { - let mp = s.m.i32(emu.max_primitives); - ( - s.m.bin(e, Bin::UDiv, tri, mp), - s.m.bin(e, Bin::URem, tri, mp), - ) - }; - - let group_stride = s.m.i32(emu.group_bytes()); - let group_base = s.m.bin(e, Bin::Mul, group_idx, group_stride); - let k2 = s.m.i32(2); - let prim_byte = s.m.bin(e, Bin::Shl, prim_idx, k2); - let idx_off = s.m.bin(e, Bin::Add, group_base, prim_byte); - - let idx_load = { - let mask1 = s.m.i8(1); - let align4 = s.m.i32(4); - s.op( - e, - "rawBufferLoad.f32", - Attr::ReadOnly, - s.t.res_ret, - 139, - &[buf, idx_off, undef_i32, mask1, align4], - ) - }; - let idx_f = s.m.extract(e, idx_load, 0); - let packed = s.m.cast(e, Cast::Bitcast, idx_f, i32t); - let zero_i = s.m.i32(0); - let culled = s.m.cmp(e, pred::SLT, packed, zero_i); - - let cull_bb = s.m.new_block(); - let draw_bb = s.m.new_block(); - s.m.terminate(e, Term::CondBr(culled, cull_bb, draw_bb)); - - // Culled primitive: write quiet NaN to SV_Position so the rasterizer drops - // the triangle regardless of depth-clip settings, and zero other outputs. - for (id, out) in plan.iter().enumerate() { - for c in 0..out.sig.cols { - let (suffix, val) = if out.sig.kind == 3 { - (".f32", s.m.f32(0x7FC0_0000)) - } else if out.sig.comp == 9 { - (".f32", s.m.f32(0)) - } else { - (".i32", zero_i) - }; - let id_k = s.m.i32(id as u32); - let col_k = s.m.i8(c); - s.op( - cull_bb, - &format!("storeOutput{suffix}"), - Attr::NoUnwind, - s.t.void, - 5, - &[id_k, zero_i, col_k, val], - ); - } - } - s.m.terminate(cull_bb, Term::Ret); - - // Active primitive: load vertex and/or per-primitive attributes and store them. - let needs_vert = plan - .iter() - .any(|o| matches!(o.src, OutputSource::Vertex { .. })); - let needs_prim = plan - .iter() - .any(|o| matches!(o.src, OutputSource::Prim { .. })); - - let v_base = if needs_vert { - let k10 = s.m.i32(10); - let shift = s.m.bin(draw_bb, Bin::Mul, corner, k10); - let shifted = s.m.bin(draw_bb, Bin::LShr, packed, shift); - let mask = s.m.i32(0x3FF); - let v_raw = s.m.bin(draw_bb, Bin::And, shifted, mask); - let mv = s.m.i32(emu.max_vertices); - let in_bounds = s.m.cmp(draw_bb, pred::IULT, v_raw, mv); - let last_v = s.m.i32(emu.max_vertices - 1); - let v_idx = s.m.select(draw_bb, in_bounds, v_raw, last_v); - let v_stride = s.m.i32(emu.vertex_stride_bytes()); - let v_rel = s.m.bin(draw_bb, Bin::Mul, v_idx, v_stride); - let v_off_base = s.m.i32(emu.vertex_offset_bytes()); - let v_off = s.m.bin(draw_bb, Bin::Add, v_off_base, v_rel); - Some(s.m.bin(draw_bb, Bin::Add, group_base, v_off)) - } else { - None - }; - - let p_base = if needs_prim { - let p_stride = s.m.i32(emu.prim_stride_bytes()); - let p_rel = s.m.bin(draw_bb, Bin::Mul, prim_idx, p_stride); - let p_off_base = s.m.i32(emu.prim_offset_bytes()); - let p_off = s.m.bin(draw_bb, Bin::Add, p_off_base, p_rel); - Some(s.m.bin(draw_bb, Bin::Add, group_base, p_off)) - } else { - None - }; - - let zero_f = s.m.f32(0); - let align4 = s.m.i32(4); - for (id, out) in plan.iter().enumerate() { - let (base, dword_offset, avail_cols) = match out.src { - OutputSource::Vertex { - dword_offset, - avail_cols, - } => (v_base.expect("vertex base"), dword_offset, avail_cols), - OutputSource::Prim { - dword_offset, - avail_cols, - } => (p_base.expect("prim base"), dword_offset, avail_cols), - OutputSource::Zero => { - for c in 0..out.sig.cols { - let (suffix, val) = if out.sig.comp == 9 { - (".f32", zero_f) - } else { - (".i32", zero_i) - }; - let id_k = s.m.i32(id as u32); - let col_k = s.m.i8(c); - s.op( - draw_bb, - &format!("storeOutput{suffix}"), - Attr::NoUnwind, - s.t.void, - 5, - &[id_k, zero_i, col_k, val], - ); - } - continue; - } - }; - - let load_cols = out.sig.cols.min(avail_cols).min(4); - let loaded = if load_cols > 0 { - let addr = if dword_offset == 0 { - base - } else { - let disp = s.m.i32(dword_offset * 4); - s.m.bin(draw_bb, Bin::Add, base, disp) - }; - let mask = s.m.i8((1u8 << load_cols) - 1); - Some(s.op( - draw_bb, - "rawBufferLoad.f32", - Attr::ReadOnly, - s.t.res_ret, - 139, - &[buf, addr, undef_i32, mask, align4], - )) - } else { - None - }; - - for c in 0..out.sig.cols { - let (suffix, val) = match loaded { - Some(agg) if c < load_cols => { - let f = s.m.extract(draw_bb, agg, u32::from(c)); - if out.sig.comp == 9 { - (".f32", f) - } else { - (".i32", s.m.cast(draw_bb, Cast::Bitcast, f, i32t)) - } - } - _ if out.sig.comp == 9 => (".f32", zero_f), - _ => (".i32", zero_i), - }; - let id_k = s.m.i32(id as u32); - let col_k = s.m.i8(c); - s.op( - draw_bb, - &format!("storeOutput{suffix}"), - Attr::NoUnwind, - s.t.void, - 5, - &[id_k, zero_i, col_k, val], - ); - } - } - s.m.terminate(draw_bb, Term::Ret); - Ok(s.finish()) -} - -fn build_output_plan( - emu: &MeshEmu, - ps_dxil: Option<&[u8]>, -) -> Result, ShaderError> { - let mut plan = Vec::new(); - let mut occupied: BTreeMap = BTreeMap::new(); - let mut next_row: u32 = 0; - - fn occupy(occupied: &mut BTreeMap, next_row: &mut u32, row: u32, col: u8, cols: u8) { - let mask = ((1u8 << cols.min(4)) - 1) << col.min(3); - *occupied.entry(row).or_default() |= mask; - *next_row = (*next_row).max(row + 1); - } - - let mut emitted_sys: Vec<(u8, u32)> = Vec::new(); - - if let Some(ps_bytes) = ps_dxil { - let c = Container::parse(ps_bytes)?; - let ps_inputs = match c.part(FourCC::ISG1) { - Some(part) => super::signature(part.data)?, - None => Vec::new(), - }; - let ps_interps = c - .part(FourCC::PSV0) - .map(|p| psv_input_interps(p.data)) - .unwrap_or_default(); - - for pi in &ps_inputs { - if !matches!(pi.kind, 0 | 3 | 4 | 5 | 6 | 7) { - continue; - } - let (found, from_prim) = match find_mesh_output(&emu.vertex_outputs, pi) { - Some(o) => (Some(o), false), - None => match find_mesh_output(&emu.prim_outputs, pi) { - Some(o) => (Some(o), true), - None => (None, false), - }, - }; - let row = pi.row.unwrap_or(next_row); - let (col, cols) = if pi.kind == 3 { - (0, 4) - } else { - (pi.col, pi.cols) - }; - let src = match found { - Some(o) if pi.kind == 3 => OutputSource::Vertex { - dword_offset: o.dword_offset, - avail_cols: o.cols, - }, - Some(o) if col >= o.col && (col - o.col) < o.cols => { - let skip = u32::from(col - o.col); - let avail_cols = o.cols - skip as u8; - let dword_offset = o.dword_offset + skip; - if from_prim { - OutputSource::Prim { - dword_offset, - avail_cols, - } - } else { - OutputSource::Vertex { - dword_offset, - avail_cols, - } - } - } - _ => OutputSource::Zero, - }; - - let ps_interp = ps_interps - .iter() - .find(|&&(r, c, k, _)| r == row && c == pi.col && k == pi.kind) - .map(|&(_, _, _, m)| m) - .unwrap_or(0); - let interp = match pi.kind { - 3 => 4, - 4 | 5 => 1, - 6 | 7 => 2, - _ => match ps_interp { - 1 => 1, - 2 | 3 | 6 => 2, - 4 | 5 | 7 => 4, - _ if from_prim => 1, - _ if pi.comp == 9 => 2, - _ => 1, - }, - }; - - if pi.kind != 0 { - emitted_sys.push((pi.kind, pi.index)); - } - occupy(&mut occupied, &mut next_row, row, col, cols); - plan.push(UnpackOutput { - sig: SigElement { - name: pi.name.clone(), - index: pi.index, - kind: pi.kind, - comp: pi.comp, - interp, - row: Some(row), - col, - cols, - usage: (1u8 << cols) - 1, - half: false, - }, - src, - }); - } - } - - for (outputs, from_prim) in [(&emu.vertex_outputs, false), (&emu.prim_outputs, true)] { - for o in outputs { - if !matches!(o.kind, 3..=7) { - continue; - } - if emitted_sys.contains(&(o.kind, o.index)) { - continue; - } - emitted_sys.push((o.kind, o.index)); - let mask = ((1u8 << o.cols.min(4)) - 1) << o.col.min(3); - let (row, col) = match o.row { - Some(r) if (occupied.get(&r).copied().unwrap_or(0) & mask) == 0 => (r, o.col), - _ => (next_row, 0), - }; - occupy(&mut occupied, &mut next_row, row, col, o.cols); - let interp = match o.kind { - 3 => 4, - 4 | 5 => 1, - _ if from_prim => 1, - _ => 2, - }; - let src = if from_prim { - OutputSource::Prim { - dword_offset: o.dword_offset, - avail_cols: o.cols, - } - } else { - OutputSource::Vertex { - dword_offset: o.dword_offset, - avail_cols: o.cols, - } - }; - plan.push(UnpackOutput { - sig: SigElement { - name: o.name.clone(), - index: o.index, - kind: o.kind, - comp: o.comp, - interp, - row: Some(row), - col, - cols: o.cols, - usage: (1u8 << o.cols) - 1, - half: false, - }, - src, - }); - } - } - - if !plan.iter().any(|o| o.sig.kind == 3) { - let row = next_row; - plan.push(UnpackOutput { - sig: SigElement { - name: "SV_Position".into(), - index: 0, - kind: 3, - comp: 9, - interp: 4, - row: Some(row), - col: 0, - cols: 4, - usage: 0xF, - half: false, - }, - src: OutputSource::Zero, - }); - } - - Ok(plan) -} - -fn find_mesh_output<'a>(outputs: &'a [MeshOutput], pi: &SigElement) -> Option<&'a MeshOutput> { - let matches = |o: &&MeshOutput| { - if pi.kind != 0 { - o.kind == pi.kind && o.index == pi.index - } else { - o.kind == 0 && o.index == pi.index && o.name.eq_ignore_ascii_case(&pi.name) - } - }; - outputs - .iter() - .find(|o| matches(o) && o.col == pi.col) - .or_else(|| outputs.iter().find(matches)) -} - -/// Reads `(row, col, kind, interp)` tuples for `PSV0` input signature elements. -fn psv_input_interps(psv: &[u8]) -> Vec<(u32, u8, u8, u8)> { - let Ok(info_size) = u32_at(psv, 0).map(|n| n as usize) else { - return Vec::new(); - }; - if info_size < 32 || psv.len() < 4 + info_size { - return Vec::new(); - } - let input_count = usize::from(psv[4 + 28]); - let mut at = 4 + info_size; - let Ok(binding_count) = u32_at(psv, at).map(|n| n as usize) else { - return Vec::new(); - }; - at += 4; - if binding_count > 0 { - let Ok(entry_size) = u32_at(psv, at).map(|n| n as usize) else { - return Vec::new(); - }; - at += 4; - at = match binding_count - .checked_mul(entry_size) - .and_then(|n| at.checked_add(n)) - { - Some(next) if next <= psv.len() => next, - _ => return Vec::new(), - }; - } - let Ok(string_bytes) = u32_at(psv, at).map(|n| n as usize) else { - return Vec::new(); - }; - at += 4; - if at + string_bytes > psv.len() { - return Vec::new(); - } - at += string_bytes; - let Ok(indices_count) = u32_at(psv, at).map(|n| n as usize) else { - return Vec::new(); - }; - at += 4; - if at + indices_count * 4 > psv.len() { - return Vec::new(); - } - at += indices_count * 4; - if at + 4 > psv.len() { - return Vec::new(); - } - let Ok(elem_size) = u32_at(psv, at).map(|n| n as usize) else { - return Vec::new(); - }; - at += 4; - if elem_size < 14 { - return Vec::new(); - } - let mut out = Vec::new(); - for k in 0..input_count { - let Some(e) = psv.get(at + k * elem_size..at + (k + 1) * elem_size) else { - break; - }; - let alloc = e[10]; - if alloc & 0x40 == 0 { - continue; - } - let row = u32::from(e[9]); - let col = (alloc >> 4) & 3; - let kind = e[11]; - let interp = e[13]; - out.push((row, col, kind, interp)); - } - out -} - -#[cfg(test)] -mod unpack_tests { - use super::*; - - #[test] - fn depth_only_unpack_shader_is_a_container() { - let emu = MeshEmu { - threads: 32, - max_vertices: 3, - max_primitives: 1, - vertex_dwords: 4, - prim_dwords: 0, - reads_group_id: false, - vertex_outputs: vec![MeshOutput { - name: "SV_Position".into(), - index: 0, - kind: 3, - comp: 9, - interp: 4, - row: Some(0), - col: 0, - cols: 4, - dword_offset: 0, - }], - prim_outputs: Vec::new(), - }; - let vs = unpack_vertex_shader(&emu, None).unwrap(); - let c = Container::parse(&vs).unwrap(); - let osg = super::super::signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); - assert_eq!(osg.len(), 1); - assert_eq!(osg[0].name, "SV_Position"); - assert_eq!(osg[0].kind, 3); - } -} - -#[cfg(all(test, windows))] -mod tests { - use super::super::validator::Validator; - use super::*; - - fn fake_ps_container(inputs: &[SigElement]) -> Vec { - let mut s = Shader::new(true); - s.inputs = inputs.to_vec(); - s.outputs = vec![SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 0xF, - half: false, - }]; - let b = s.entry; - let zero = s.m.f32(0); - for c in 0..4u8 { - let zero_i = s.m.i32(0); - let col_k = s.m.i8(c); - s.op( - b, - "storeOutput.f32", - Attr::NoUnwind, - s.t.void, - 5, - &[zero_i, zero_i, col_k, zero], - ); - } - s.m.terminate(b, Term::Ret); - s.finish() - } - - #[test] - fn unpack_vs_signature_matches_ps_with_per_primitive_outputs() { - let emu = MeshEmu { - threads: 32, - max_vertices: 16, - max_primitives: 8, - vertex_dwords: 8, - prim_dwords: 4, - reads_group_id: false, - vertex_outputs: vec![ - MeshOutput { - name: "SV_Position".into(), - index: 0, - kind: 3, - comp: 9, - interp: 4, - row: Some(0), - col: 0, - cols: 4, - dword_offset: 0, - }, - MeshOutput { - name: "COLOR".into(), - index: 0, - kind: 0, - comp: 9, - interp: 2, - row: Some(1), - col: 0, - cols: 4, - dword_offset: 4, - }, - ], - prim_outputs: vec![MeshOutput { - name: "PRIMDATA".into(), - index: 0, - kind: 0, - comp: 9, - interp: 1, - row: Some(0), - col: 0, - cols: 4, - dword_offset: 0, - }], - }; - - // PS places COLOR0 at row 0 (colliding with MS SV_Position row 0!) - // and PRIMDATA at row 1, without reading SV_Position. - let ps = fake_ps_container(&[ - SigElement { - name: "COLOR".into(), - index: 0, - kind: 0, - comp: 9, - interp: 2, - row: Some(0), - col: 0, - cols: 4, - usage: 0xF, - half: false, - }, - SigElement { - name: "PRIMDATA".into(), - index: 0, - kind: 0, - comp: 9, - interp: 1, - row: Some(1), - col: 0, - cols: 4, - usage: 0xF, - half: false, - }, - ]); - - let mut vs = unpack_vertex_shader(&emu, Some(&ps)).unwrap(); - let c = Container::parse(&vs).unwrap(); - let osg1 = super::super::signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); - assert_eq!(osg1.len(), 3); - assert_eq!(osg1[0].name, "COLOR"); - assert_eq!(osg1[0].row, Some(0)); - assert_eq!(osg1[1].name, "PRIMDATA"); - assert_eq!(osg1[1].row, Some(1)); - assert_eq!(osg1[2].name, "SV_Position"); - assert_eq!(osg1[2].row, Some(2)); - assert_eq!( - psv_input_interps(c.part(FourCC::PSV0).unwrap().data), - vec![(0, 0, 1, 0)] - ); - let ps_c = Container::parse(&ps).unwrap(); - assert_eq!( - psv_input_interps(ps_c.part(FourCC::PSV0).unwrap().data), - vec![(0, 0, 0, 2), (1, 0, 0, 1)] - ); - - // Depth-only pipeline (ps == None) still emits SV_Position. - let mut depth_vs = unpack_vertex_shader(&emu, None).unwrap(); - let dc = Container::parse(&depth_vs).unwrap(); - let dosg = super::super::signature(dc.part(FourCC::OSG1).unwrap().data).unwrap(); - assert_eq!(dosg.len(), 1); - assert_eq!(dosg[0].kind, 3); - - if let Ok(mut v) = Validator::load(Validator::default_path().as_deref()) { - v.validate(&mut vs).unwrap(); - v.validate(&mut depth_vs).unwrap(); - } - } - - use super::super::host::{EmulatedMeshDraw, Host}; - use super::super::{HostShader, emit_with}; - use crate::native::{HwStage, MeshIo, NativeProgram, PsInput, StageIo, Usage, VsOutput}; - use crate::{io, ir, resource, structure}; - - const S_ENDPGM: u32 = 0xBF81_0000; - const S_BARRIER: u32 = 0xBF8A_0000; - - const fn sgpr(n: u8) -> u16 { - n as u16 - } - - const fn vgpr(n: u8) -> u16 { - 256 + n as u16 - } - - const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 { - 0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) - } - - const fn vop1_lit(op: u16, vdst: u8, lit: u32) -> [u32; 2] { - [vop1(op, vdst, 0xFF), lit] - } - - const fn vop2(op: u16, vdst: u8, src0: u16, vsrc1: u8) -> u32 { - (op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) - } - - const fn vopc(op: u16, src0: u16, vsrc1: u8) -> u32 { - 0x7C00_0000 | (op as u32 & 0xFF) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) - } - - const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { - [ - 0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32, - (src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18, - ] - } - - const fn ds(op: u8, vdst: u8, vaddr: u8, vdata0: u8, vdata1: u8, offset: u16) -> [u32; 2] { - [ - 0xD800_0000 | (op as u32) << 18 | offset as u32, - (vdst as u32) << 24 | (vdata1 as u32) << 16 | (vdata0 as u32) << 8 | vaddr as u32, - ] - } - - const fn exp(target: u8, en: u8, v: [u8; 4], done: bool, vm: bool) -> [u32; 2] { - [ - 0x3E << 26 - | (vm as u32) << 12 - | (done as u32) << 11 - | (target as u32 & 0x3F) << 4 - | (en as u32 & 0xF), - (v[0] as u32) | (v[1] as u32) << 8 | (v[2] as u32) << 16 | (v[3] as u32) << 24, - ] - } - - const fn v_interp_mov_f32(vdst: u8, attr: u8, chan: u8) -> u32 { - 0xC800_0000 | (vdst as u32) << 18 | 2 << 16 | (attr as u32) << 10 | (chan as u32) << 8 | 2 - } - - fn sig_el(name: &str, kind: u8, comp: u8, row: Option, usage: u8) -> SigElement { - SigElement { - name: name.into(), - index: 0, - kind, - comp, - interp: 0, - row, - col: 0, - cols: 4, - usage, - half: false, - } - } - - fn compile_ms( - words: &[u32], - io_outputs: Vec, - osg1: &[SigElement], - psg1: &[SigElement], - (threads, max_vertices, max_primitives, lds_bytes): (u32, u32, u32, u32), - ) -> HostShader { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Ms, - wave64: false, - vgprs: 32, - layout: Vec::new(), - used: Vec::new(), - io: StageIo::Ms(MeshIo { - outputs: io_outputs, - clip_cntl: 0, - threads, - max_vertices, - max_primitives, - topology: 2, - lds_bytes, - }), - code, - }; - let osg_bytes = super::super::container::signature(osg1, false); - let psg_bytes = super::super::container::signature(psg1, false); - let container_bytes = - crate::dxbc::build(&[(FourCC::OSG1, &osg_bytes), (FourCC::PSG1, &psg_bytes)]); - let c = Container::parse(&container_bytes).unwrap(); - let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let raised = io::raise(&p, &native).unwrap(); - let shader = emit_with(&c, &native, &p, &st, &raised, &res, MeshMode::Emulate).unwrap(); - if let Ok(mut v) = Validator::load(Validator::default_path().as_deref()) { - v.validate(&mut shader.dxil.clone()) - .expect("emulated mesh CS validation failed"); - } - shader - } - - fn compile_flat_ps(semantic_name: &str) -> HostShader { - let words = [ - v_interp_mov_f32(0, 0, 0), - v_interp_mov_f32(1, 0, 1), - v_interp_mov_f32(2, 0, 2), - v_interp_mov_f32(3, 0, 3), - exp(0, 0xF, [0, 1, 2, 3], true, true)[0], - exp(0, 0xF, [0, 1, 2, 3], true, true)[1], - S_ENDPGM, - ]; - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Ps, - wave64: false, - vgprs: 8, - layout: Vec::new(), - used: Vec::new(), - io: StageIo::Ps { - inputs: vec![PsInput { - usage: Usage::Generic, - row: 0, - mask: 0xF, - attr: 0, - flat: true, - fp16: false, - pack2: false, - row2: 0, - }], - input_addr: 0, - rsrc2: 0, - db_shader_control: 0, - patches: Vec::new(), - }, - code, - }; - let isg1 = - super::super::container::signature(&[sig_el(semantic_name, 0, 9, Some(0), 0xF)], true); - let osg1 = - super::super::container::signature(&[sig_el("SV_Target", 16, 9, Some(0), 0xF)], false); - let container_bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); - let c = Container::parse(&container_bytes).unwrap(); - let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let raised = io::raise(&p, &native).unwrap(); - let shader = emit_with(&c, &native, &p, &st, &raised, &res, MeshMode::Emulate).unwrap(); - if let Ok(mut v) = Validator::load(Validator::default_path().as_deref()) { - v.validate(&mut shader.dxil.clone()) - .expect("PS validation failed"); - } - shader - } - - fn run_on_hosts(mut f: impl FnMut(&str, &Host)) { - let _one = super::super::valu_tests::ONE_AT_A_TIME - .lock() - .unwrap_or_else(|e| e.into_inner()); - let mut ran = 0; - for (label, warp) in [("hardware", false), ("warp", true)] { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; - }; - ran += 1; - f(label, &host); - } - assert!( - ran > 0 || std::env::var("CI").is_err(), - "no SM 6.6 host available" - ); - } - - #[test] - fn emulated_mesh_draws_triangle_and_culls_bit31_and_unexported() { - let build_variant = |cull_prim0: bool| { - let mut words = Vec::new(); - // v0 = tid (0..7) - words.extend(vop3(0x365, 0, 193, 128, 0)); - // Default position: (-1, -1, 0.5, 1.0) - words.extend(vop1_lit(0x001, 1, (-1.0f32).to_bits())); - words.extend(vop1_lit(0x001, 2, (-1.0f32).to_bits())); - words.extend(vop1_lit(0x001, 3, 0.5f32.to_bits())); - words.extend(vop1_lit(0x001, 4, 1.0f32.to_bits())); - // Default color: RED (1, 0, 0, 1); scratch constants v10=3.0, v11=1.0, v12=0.0 - words.extend(vop1_lit(0x001, 5, 1.0f32.to_bits())); - words.extend(vop1_lit(0x001, 6, 0.0f32.to_bits())); - words.extend(vop1_lit(0x001, 7, 0.0f32.to_bits())); - words.extend(vop1_lit(0x001, 8, 1.0f32.to_bits())); - words.extend(vop1_lit(0x001, 10, 3.0f32.to_bits())); - words.extend(vop1_lit(0x001, 11, 1.0f32.to_bits())); - words.extend(vop1_lit(0x001, 12, 0.0f32.to_bits())); - // tid == 1 or tid == 4 -> pos.x = 3.0 - words.push(vopc(0x0C2, 129, 0)); - words.push(vop2(0x001, 1, vgpr(1), 10)); - words.push(vopc(0x0C2, 132, 0)); - words.push(vop2(0x001, 1, vgpr(1), 10)); - // tid == 2 or tid == 5 -> pos.y = 3.0 - words.push(vopc(0x0C2, 130, 0)); - words.push(vop2(0x001, 2, vgpr(2), 10)); - words.push(vopc(0x0C2, 133, 0)); - words.push(vop2(0x001, 2, vgpr(2), 10)); - // tid >= 3 (3 <= tid, i.e., 3 < tid + 1 or 2 < tid) -> green (0, 1, 0, 1) - words.push(vopc(0x0C1, 130, 0)); // 2 < v0 - words.push(vop2(0x001, 5, vgpr(5), 12)); - words.push(vop2(0x001, 6, vgpr(6), 11)); - words.extend(exp(12, 0xF, [1, 2, 3, 4], false, false)); - words.extend(exp(32, 0xF, [5, 6, 7, 8], false, false)); - // v9 = (3 | 4<<10 | 5<<20) | 0x8000_0000 (bit-31 culled green tri) - words.extend(vop1_lit(0x001, 9, 0x8050_1003)); - if !cull_prim0 { - words.extend(vop1_lit(0x001, 13, 0x0020_0400)); - words.push(vopc(0x0C2, 128, 0)); // v0 == 0 - words.push(vop2(0x001, 9, vgpr(9), 13)); - } - // Only tid < 2 (2 > v0) exports `exp prim`; slot 2 relies on prologue cull. - words.push(vopc(0x0C4, 130, 0)); // 2 > v0 - words.push(0xBE80_3C6A); // s_and_saveexec_b32 s0, vcc_lo - words.push(0xBF88_0002); // s_cbranch_execz +2 - words.extend(exp(20, 0x1, [9, 0, 0, 0], true, false)); - words.push(0x887E_007E); // s_or_b32 exec_lo, exec_lo, s0 - words.push(S_ENDPGM); - - compile_ms( - &words, - vec![VsOutput { - usage: Usage::Generic, - row: 0, - param: 0, - fp16: false, - pack2: false, - }], - &[ - sig_el("SV_Position", 3, 9, None, 0xF), - sig_el("COLOR", 0, 9, Some(0), 0xF), - ], - &[], - (8, 6, 3, 0), - ) - }; - - let ms_active = build_variant(false); - let ms_culled = build_variant(true); - let ps = compile_flat_ps("COLOR"); - let emu_active = ms_active.mesh_emu.as_ref().unwrap().clone(); - let emu_culled = ms_culled.mesh_emu.as_ref().unwrap().clone(); - - run_on_hosts(|label, host| { - let pipes_active = host.emulated_mesh_pipelines(&ms_active, &ps).unwrap(); - let pixels = host - .draw_emulated_mesh( - &pipes_active, - &EmulatedMeshDraw { - cs_roots: Vec::new(), - ps_roots: Vec::new(), - size: (8, 8), - groups: 1, - max_primitives: emu_active.max_primitives, - group_bytes: emu_active.group_bytes(), - base_group: 0, - slot_map: None, - }, - ) - .unwrap_or_else(|e| panic!("{label}: active draw failed: {e}")); - assert!( - pixels.iter().all(|&p| p == [1.0, 0.0, 0.0, 1.0]), - "{label}: expected full red, got {:?}", - pixels[0] - ); - - let pipes_culled = host.emulated_mesh_pipelines(&ms_culled, &ps).unwrap(); - let pixels = host - .draw_emulated_mesh( - &pipes_culled, - &EmulatedMeshDraw { - cs_roots: Vec::new(), - ps_roots: Vec::new(), - size: (8, 8), - groups: 1, - max_primitives: emu_culled.max_primitives, - group_bytes: emu_culled.group_bytes(), - base_group: 0, - slot_map: None, - }, - ) - .unwrap_or_else(|e| panic!("{label}: culled draw failed: {e}")); - assert!( - pixels.iter().all(|&p| p == [0.0, 0.0, 0.0, 0.0]), - "{label}: expected all culled, got {:?}", - pixels[0] - ); - }); - } - - #[test] - fn emulated_mesh_group_id_supports_base_group_and_slot_map() { - let mut words = Vec::new(); - // s2 = group_id (from v5 via v_readfirstlane_b32) - words.push(vop1(0x002, 2, vgpr(5))); - // v0 = tid (0..3) - words.extend(vop3(0x365, 0, 193, 128, 0)); - // v5 = float(s2), v6 = 0, v7 = 0, v8 = 1.0 -> COLOR0.r = group_id - words.push(vop1(0x006, 5, sgpr(2))); - words.extend(vop1_lit(0x001, 6, 0.0f32.to_bits())); - words.extend(vop1_lit(0x001, 7, 0.0f32.to_bits())); - words.extend(vop1_lit(0x001, 8, 1.0f32.to_bits())); - // If s2 == 36 (group 9 * mesh_stride 4): draw right triangle (0, 1), (2, 1), (0, -3) - // covering top-right; otherwise draw left triangle (-1, 1), (0, 1), (-1, -3) covering top-left. - // v10 = 36, v11 = s2; compare vcc = (v11 == 36) - words.push(vop1(0x001, 11, sgpr(2))); - words.extend(vop1_lit(0x001, 10, 36)); - // Base left x (-1.0), vs right x (0.0) in v12 - words.extend(vop1_lit(0x001, 1, (-1.0f32).to_bits())); - words.extend(vop1_lit(0x001, 12, 0.0f32.to_bits())); - words.push(vopc(0x0C2, vgpr(10), 11)); - words.push(vop2(0x001, 1, vgpr(1), 12)); // base x: -1 or 0 - // If tid == 1: x += 1.0 (left: -1->0) or +2.0 (right: 0->2) - words.extend(vop1_lit(0x001, 13, 1.0f32.to_bits())); - words.extend(vop1_lit(0x001, 14, 2.0f32.to_bits())); - words.push(vopc(0x0C2, vgpr(10), 11)); - words.push(vop2(0x001, 13, vgpr(13), 14)); // width: 1.0 or 2.0 - words.extend(vop2_add_f32_helper(14, 1, 13)); - words.push(vopc(0x0C2, 129, 0)); // tid == 1 - words.push(vop2(0x001, 1, vgpr(1), 14)); - // y: default 1.0, tid == 2 -> -3.0; z = 0.5, w = 1.0 - words.extend(vop1_lit(0x001, 2, 1.0f32.to_bits())); - words.extend(vop1_lit(0x001, 15, (-3.0f32).to_bits())); - words.push(vopc(0x0C2, 130, 0)); // tid == 2 - words.push(vop2(0x001, 2, vgpr(2), 15)); - words.extend(vop1_lit(0x001, 3, 0.5f32.to_bits())); - words.extend(vop1_lit(0x001, 4, 1.0f32.to_bits())); - - words.extend(exp(12, 0xF, [1, 2, 3, 4], false, false)); - words.extend(exp(32, 0xF, [5, 6, 7, 8], false, false)); - words.extend(vop1_lit(0x001, 9, 0x0020_0400)); - words.extend(exp(20, 0x1, [9, 0, 0, 0], true, false)); - words.push(S_ENDPGM); - - let ms = compile_ms( - &words, - vec![VsOutput { - usage: Usage::Generic, - row: 0, - param: 0, - fp16: false, - pack2: false, - }], - &[ - sig_el("SV_Position", 3, 9, None, 0xF), - sig_el("COLOR", 0, 9, Some(0), 0xF), - ], - &[], - (4, 3, 1, 0), - ); - let emu = ms.mesh_emu.as_ref().unwrap(); - assert!(emu.reads_group_id); - let ps = compile_flat_ps("COLOR"); - - run_on_hosts(|label, host| { - let pipes = host.emulated_mesh_pipelines(&ms, &ps).unwrap(); - // Chunked direct dispatch: 1 group starting at base_group = 5 -> top-left = 5.0 - let direct = host - .draw_emulated_mesh( - &pipes, - &EmulatedMeshDraw { - cs_roots: Vec::new(), - ps_roots: Vec::new(), - size: (8, 8), - groups: 1, - max_primitives: emu.max_primitives, - group_bytes: emu.group_bytes(), - base_group: 5, - slot_map: None, - }, - ) - .unwrap_or_else(|e| panic!("{label}: base_group draw failed: {e}")); - assert_eq!(direct[0], [20.0, 0.0, 0.0, 1.0], "{label}: direct[0]"); - - // Multi-record indirect dispatch: 2 local groups reading slot_map [2, 9] - let indirect = host - .draw_emulated_mesh( - &pipes, - &EmulatedMeshDraw { - cs_roots: Vec::new(), - ps_roots: Vec::new(), - size: (8, 8), - groups: 2, - max_primitives: emu.max_primitives, - group_bytes: emu.group_bytes(), - base_group: INDIRECT_SLOT_MAP_FLAG, - slot_map: Some(&[2, 9]), - }, - ) - .unwrap_or_else(|e| panic!("{label}: slot_map draw failed: {e}")); - assert_eq!(indirect[0], [8.0, 0.0, 0.0, 1.0], "{label}: top-left"); - assert_eq!(indirect[7], [36.0, 0.0, 0.0, 1.0], "{label}: top-right"); - }); - } - - const fn vop2_add_f32_helper(vdst: u8, src0_v: u8, vsrc1: u8) -> [u32; 1] { - [vop2(0x003, vdst, vgpr(src0_v), vsrc1)] - } - - #[test] - fn emulated_mesh_passes_per_primitive_psg1_to_ps() { - let mut words = Vec::new(); - words.extend(vop3(0x365, 0, 193, 128, 0)); - words.extend(vop1_lit(0x001, 1, (-1.0f32).to_bits())); - words.extend(vop1_lit(0x001, 2, (-1.0f32).to_bits())); - words.extend(vop1_lit(0x001, 3, 0.5f32.to_bits())); - words.extend(vop1_lit(0x001, 4, 1.0f32.to_bits())); - words.extend(vop1_lit(0x001, 10, 3.0f32.to_bits())); - words.push(vopc(0x0C2, 129, 0)); - words.push(vop2(0x001, 1, vgpr(1), 10)); - words.push(vopc(0x0C2, 130, 0)); - words.push(vop2(0x001, 2, vgpr(2), 10)); - words.extend(exp(12, 0xF, [1, 2, 3, 4], false, false)); - - words.extend(vop1_lit(0x001, 5, 0.25f32.to_bits())); - words.extend(vop1_lit(0x001, 6, 0.5f32.to_bits())); - words.extend(vop1_lit(0x001, 7, 0.75f32.to_bits())); - words.extend(vop1_lit(0x001, 8, 1.0f32.to_bits())); - // Per-primitive parameter 0 (`param = 0x80` -> PSG1 PRIMCOLOR at row 0) - words.extend(exp(32, 0xF, [5, 6, 7, 8], false, false)); - - words.extend(vop1_lit(0x001, 9, 0x0020_0400)); - words.extend(exp(20, 0x1, [9, 0, 0, 0], true, false)); - words.push(S_ENDPGM); - - let ms = compile_ms( - &words, - vec![VsOutput { - usage: Usage::Generic, - row: 0, - param: 0x80, - fp16: false, - pack2: false, - }], - &[sig_el("SV_Position", 3, 9, None, 0xF)], - &[sig_el("PRIMCOLOR", 0, 9, Some(0), 0xF)], - (4, 3, 1, 0), - ); - let ps = compile_flat_ps("PRIMCOLOR"); - let emu = ms.mesh_emu.as_ref().unwrap().clone(); - - run_on_hosts(|label, host| { - let pipes = host.emulated_mesh_pipelines(&ms, &ps).unwrap(); - let pixels = host - .draw_emulated_mesh( - &pipes, - &EmulatedMeshDraw { - cs_roots: Vec::new(), - ps_roots: Vec::new(), - size: (8, 8), - groups: 1, - max_primitives: emu.max_primitives, - group_bytes: emu.group_bytes(), - base_group: 0, - slot_map: None, - }, - ) - .unwrap_or_else(|e| panic!("{label}: draw failed: {e}")); - assert!( - pixels.iter().all(|&p| p == [0.25, 0.5, 0.75, 1.0]), - "{label}: expected [0.25, 0.5, 0.75, 1.0], got {:?}", - pixels[0] - ); - }); - } - - #[test] - fn emulated_mesh_supports_lds_barrier_and_quad_swizzle() { - let mut words = Vec::new(); - // v0 = tid (0..3) - words.extend(vop3(0x365, 0, 193, 128, 0)); - // v14 = tid * 4 (LDS byte offset) - words.push(vop2(0x01A, 14, 130, 0)); // v_lshlrev_b32 v14, 2, v0 - // v15 = float(tid + 1) * 0.25 -> thread 2 writes 0.75 into lds[8] - words.push(vop2(0x025, 15, 129, 0)); // v_add_nc_u32 v15, 1, v0 - words.push(vop1(0x006, 15, vgpr(15))); // v_cvt_f32_u32 v15, v15 - words.extend(vop1_lit(0x001, 16, 0.25f32.to_bits())); - words.push(vop2(0x008, 15, vgpr(15), 16)); // v_mul_f32 v15, v15, v16 - words.extend(ds(0x0D, 0, 14, 15, 0, 0)); // ds_write_b32 v14, v15 - words.push(S_BARRIER); - // Each lane reads ((tid + 3) & 3) * 4 -> lane 3 reads lds[8] (0.75) - words.push(vop2(0x025, 14, 131, 0)); // v_add_nc_u32 v14, 3, v0 - words.push(vop2(0x01B, 14, 131, 14)); // v_and_b32 v14, 3, v14 - words.push(vop2(0x01A, 14, 130, 14)); // v_lshlrev_b32 v14, 2, v14 - words.extend(ds(0x36, 5, 14, 0, 0, 0)); // ds_read_b32 v5, v14 - // Broadcast quad lane 3's value (0.75) to all 4 lanes in the quad - words.extend(ds(0x35, 5, 5, 0, 0, 0x80FF)); // ds_swizzle_b32 v5, v5 offset:0x80FF - - // Position + COLOR(v5, 0, 0, 1) - words.extend(vop1_lit(0x001, 1, (-1.0f32).to_bits())); - words.extend(vop1_lit(0x001, 2, (-1.0f32).to_bits())); - words.extend(vop1_lit(0x001, 3, 0.5f32.to_bits())); - words.extend(vop1_lit(0x001, 4, 1.0f32.to_bits())); - words.extend(vop1_lit(0x001, 10, 3.0f32.to_bits())); - words.push(vopc(0x0C2, 129, 0)); - words.push(vop2(0x001, 1, vgpr(1), 10)); - words.push(vopc(0x0C2, 130, 0)); - words.push(vop2(0x001, 2, vgpr(2), 10)); - words.extend(vop1_lit(0x001, 6, 0.0f32.to_bits())); - words.extend(vop1_lit(0x001, 7, 0.0f32.to_bits())); - words.extend(vop1_lit(0x001, 8, 1.0f32.to_bits())); - words.extend(exp(12, 0xF, [1, 2, 3, 4], false, false)); - words.extend(exp(32, 0xF, [5, 6, 7, 8], false, false)); - words.extend(vop1_lit(0x001, 9, 0x0020_0400)); - words.extend(exp(20, 0x1, [9, 0, 0, 0], true, false)); - words.push(S_ENDPGM); - - let ms = compile_ms( - &words, - vec![VsOutput { - usage: Usage::Generic, - row: 0, - param: 0, - fp16: false, - pack2: false, - }], - &[ - sig_el("SV_Position", 3, 9, None, 0xF), - sig_el("COLOR", 0, 9, Some(0), 0xF), - ], - &[], - (4, 3, 1, 16), - ); - let ps = compile_flat_ps("COLOR"); - let emu = ms.mesh_emu.as_ref().unwrap().clone(); - - run_on_hosts(|label, host| { - let pipes = host.emulated_mesh_pipelines(&ms, &ps).unwrap(); - let pixels = host - .draw_emulated_mesh( - &pipes, - &EmulatedMeshDraw { - cs_roots: Vec::new(), - ps_roots: Vec::new(), - size: (8, 8), - groups: 1, - max_primitives: emu.max_primitives, - group_bytes: emu.group_bytes(), - base_group: 0, - slot_map: None, - }, - ) - .unwrap_or_else(|e| panic!("{label}: draw failed: {e}")); - assert!( - pixels.iter().all(|&p| p == [0.75, 0.0, 0.0, 1.0]), - "{label}: expected [0.75, 0.0, 0.0, 1.0], got {:?}", - pixels[0] - ); - }); - } -} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0a13cdb..275ba13 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -29,7 +29,7 @@ //! `b` / `t` in [`ROOT_CBV_SPACE`], `i` the title's root parameter //! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the //! address the title sets is the buffer's. -//! * **Vertex fetch** (added 2026-11-23). Grand Theft Auto VI's mesh and +//! * **Vertex fetch** (added 2026-11-23). The title's mesh and //! vertex programs fetch vertices themselves with typed-format loads //! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm, //! 2_10_10_10 unorm, 8_8_8_8 and 16_16_16_16 uint...) is in the @@ -80,27 +80,17 @@ //! shaders and draws triangle lists with the title's own vertex counts. //! It binds nothing. -pub mod address_map; mod bitcode; -#[cfg(test)] -mod bvh_tests; mod container; #[cfg(all(test, windows))] mod diff_tests; -#[cfg(all(windows, any(test, feature = "host")))] -pub mod host; -#[cfg(all(test, windows))] -mod image_atomic_tests; #[cfg(all(test, windows))] mod intersect_tests; +#[cfg(all(windows, any(test, feature = "host")))] +pub mod host; mod lower; -mod mesh_emu; -#[cfg(test)] -mod mtbuf_tests; mod own_bits; mod rect; -#[cfg(all(test, windows))] -mod root_view_tests; mod sampler; mod shader; mod threading; @@ -110,26 +100,25 @@ pub mod validator; mod valu_tests; #[cfg(all(test, windows))] mod waterfall_tests; -mod wave; #[cfg(all(test, windows))] mod wave64_tests; +mod wave; use crate::dxbc::{Container, FourCC}; use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; +pub use bitcode::census; +pub use sampler::StaticSampler; pub use lower::set_host_max_wave; -pub use mesh_emu::{INDIRECT_SLOT_MAP_FLAG, MeshEmu, MeshMode, MeshOutput, unpack_vertex_shader}; pub use rect::rect_list_gs; -pub use sampler::StaticSampler; pub use shader::{ - ADDRESS_MAP_SPACE, DESCRIPTOR_WORDS_SPACE, MEMORY_FAULTS, MEMORY_PAGES, MESH_EMU_SPACE, - ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, SLOT_STRIDES_COUNT, - USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, set_view_heap_limit, - view_heap_limit, + MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, + SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, + set_view_heap_limit, view_heap_limit, }; -/// The loop limit without an override: 2^14. +/// The loop limit without an override: 2^20. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; /// The iteration count after which a translated loop is left, per lane and @@ -137,8 +126,8 @@ pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; /// /// With the `diagnostics` feature, `VICTORY_SHADER_LOOP_LIMIT` (decimal or /// `0x` hex, at least 1) sets it instead. A loop that hits the limit in -/// every lane of a full-screen pass still runs long (2^14 times a 4K -/// screen is about 10^11 iterations); a much lower limit shows whether +/// every lane of a full-screen pass still runs for seconds (2^20 times a +/// 4K screen is about 10^13 iterations); a much lower limit shows whether /// such loops are what makes a frame slow. The value is part of the /// translation, so the shader cache must key on it (`victory-gpu`'s does). pub fn loop_limit() -> u32 { @@ -152,40 +141,6 @@ pub fn loop_limit() -> u32 { }) } -/// Whether translated loops leave breadcrumbs: with the `diagnostics` feature -/// and `VICTORY_SHADER_BREADCRUMBS=1`, each loop of a shader stores its -/// iteration count (`atomicMax`) in a host buffer, so that after a hung or -/// removed device the host can name the shaders whose loops ran away. The -/// buffer is `BREADCRUMB_SLOTS` slots of `BREADCRUMB_LOOPS` words, a -/// shader's slot taken from its container's digest ([`breadcrumb_slot`]); -/// the shader finds the buffer's UAV in the bound view heap, at the index -/// the host passes in the user-data dword of root type [`BREADCRUMB_ROOT`] -/// (the first past the console's). Off, nothing changes: not the code, nor -/// the root signature, nor the shader cache's key. The value is part of the -/// translation, so the shader cache must key on it (`victory-gpu`'s does). -pub fn breadcrumbs() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - cfg!(feature = "diagnostics") - && std::env::var("VICTORY_SHADER_BREADCRUMBS").is_ok_and(|v| v.trim() == "1") - }) -} - -/// The root type of the user-data dword that holds the heap index of the -/// breadcrumb buffer's UAV (see [`breadcrumbs`]). -pub const BREADCRUMB_ROOT: crate::native::RootType = crate::native::RootType::Other(0x00B8_EADC); - -/// Slots of the breadcrumb buffer, and loops (words) per slot: a shader -/// beyond the eighth loop leaves none for it. -pub const BREADCRUMB_SLOTS: u32 = 1024; -pub const BREADCRUMB_LOOPS: u32 = 8; - -/// The breadcrumb slot of the shader whose container has `digest` (two -/// shaders may share one; the host lists them all). -pub fn breadcrumb_slot(digest: &[u8; 16]) -> u32 { - (u32::from(digest[0]) | u32::from(digest[1]) << 8) % BREADCRUMB_SLOTS -} - /// Which of a translated program's group barriers wait for the whole /// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory /// fence and lose the wait. A wait that some thread of the group never @@ -206,19 +161,45 @@ pub fn breadcrumb_slot(digest: &[u8; 16]) -> u32 { /// does). pub fn group_sync() -> u8 { static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); - *MODE.get_or_init(|| { - match std::env::var("VICTORY_GROUP_SYNC") - .ok() - .as_deref() - .map(str::trim) - { - Some("0") => 0, - Some("1") => 1, - _ => 2, - } + *MODE.get_or_init(|| match std::env::var("VICTORY_GROUP_SYNC").ok().as_deref().map(str::trim) { + Some("0") => 0, + Some("1") => 1, + _ => 2, }) } +/// The clean-up passes that run over a translated program before it is +/// written (`bitcode::opt`): a set of that module's pass bits. Every pass +/// is exact, so the switch is for telling a translator fault from a +/// clean-up fault, and for measuring what the clean-up is worth. +/// `VICTORY_SHADER_OPT`: +/// - unset: every pass. +/// - `0`: none (the module as the lowering made it). +/// - a number (decimal or `0x` hex): those passes; 1 dead code, 2 constants +/// and identities, 4 one instruction for one value, 8 what a branch taken +/// says about its condition, 16 one read for one place within a block, +/// 32 a first-lane read of two host waves without the round that asks +/// which half has a lane (where every lane has one). +/// +/// Part of the translation: the shader cache keys on it (`victory-gpu`'s +/// does). +pub fn shader_opt() -> u32 { + static PASSES: std::sync::OnceLock = std::sync::OnceLock::new(); + *PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref())) +} + +/// `VICTORY_SHADER_OPT`'s value; every pass when it is unset or +/// unreadable. Pure, for testing. +fn parse_shader_opt(value: Option<&str>) -> u32 { + let parsed = value + .map(str::trim) + .and_then(|v| match v.strip_prefix("0x") { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => v.parse().ok(), + }); + parsed.map_or(bitcode::opt::ALL, |n| n & bitcode::opt::ALL) +} + /// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset, /// unreadable or 0. Pure, for testing. fn parse_loop_limit(value: Option<&str>) -> u32 { @@ -253,25 +234,11 @@ pub struct HostShader { /// Root SRVs (raw buffers) the shader reads: `t` in /// [`ROOT_CBV_SPACE`]. pub root_srvs: Vec, - /// The shader reads title memory at addresses it computes (pointers - /// it loads, a BVH it walks): the host binds the address map as a - /// root SRV, `t0` in [`ADDRESS_MAP_SPACE`]. See [`address_map`] for - /// its layout. - pub address_map: bool, - /// The shader reads descriptors as numbers (a buffer's address, say): - /// the host binds the console words of the view heap's descriptors, 32 - /// bytes per slot as the console lays them out, as a root SRV, `t0` in - /// [`DESCRIPTOR_WORDS_SPACE`]. A slot whose words the host cannot give - /// reads zero. - pub descriptor_words: bool, /// Root UAVs (raw buffers) the shader reads or writes: `u` in /// [`ROOT_CBV_SPACE`]. pub root_uavs: Vec, /// Heap descriptors that can be selected from root state at bind time. pub root_indexed_views: Vec, - /// Populated when a mesh program (`HwStage::Ms`) was translated in - /// [`MeshMode::Emulate`] mode as a `cs_6_6` compute shader. - pub mesh_emu: Option, } impl HostShader { @@ -302,14 +269,8 @@ pub struct UserData { } /// Translates the vertex, pixel, compute or mesh program of a console -/// shader container with native mesh output. +/// shader container. pub fn translate(container: &[u8]) -> Result { - translate_with(container, MeshMode::Native) -} - -/// Translates the vertex, pixel, compute or mesh program of a console -/// shader container using `mesh` mode for mesh programs (`HwStage::Ms`). -pub fn translate_with(container: &[u8], mesh: MeshMode) -> Result { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) @@ -333,10 +294,10 @@ pub fn translate_with(container: &[u8], mesh: MeshMode) -> Result Result { - emit_with(c, native, p, st, io, res, MeshMode::Native) -} - -/// Emits a program whose earlier stages already ran, using `mesh` mode for -/// mesh programs (`HwStage::Ms`). -pub fn emit_with( - c: &Container, - native: &NativeProgram, - p: &ir::Program, - st: &structure::Structured, - io: &io::Io, - res: &resource::Resources, - mesh: MeshMode, ) -> Result { // (what an earlier program's lowering on this thread left behind) lower::take_needs(); - let original = emit_program(c, native, p, st, io, res, mesh); + let original = emit_program(c, native, p, st, io, res); // A console wave64 compute program on a host of 32-lane waves that // still needs 64 lanes, or whose cross-lane code sits where not every // lane runs: once more with its early-outs left out @@ -399,9 +346,7 @@ pub fn emit_with( Ok(()) => true, Err((offset, what)) => { if why { - eprintln!( - "WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}" - ); + eprintln!("WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}"); } false } @@ -422,7 +367,7 @@ pub fn emit_with( ]; for (name, f) in &forms { if let Some((p, st, io, res)) = f { - let again = emit_program(c, native, p, st, io, res, mesh); + let again = emit_program(c, native, p, st, io, res); report(name, &again); if done(&again) { return again.map(|(shader, _)| shader); @@ -445,13 +390,9 @@ pub fn emit_with( // lane runs, where the two host waves can exchange. // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.) let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0"); - let deep = if deep_on { - form(ir::without_skips(p, true)) - } else { - None - }; + let deep = if deep_on { form(ir::without_skips(p, true)) } else { None }; if let Some((p, st, io, res)) = &deep { - let again = emit_program(c, native, p, st, io, res, mesh); + let again = emit_program(c, native, p, st, io, res); report("without skips, scalars followed", &again); if done(&again) { return again.map(|(shader, _)| shader); @@ -486,31 +427,16 @@ pub fn emit_with( if let Some((p, st, io, res)) = f && idiom(p, st) == exact { - let local = - lower::with_local_waves(|| emit_program(c, native, p, st, io, res, mesh)); - report( - &format!( - "local waves ({}), {name}", - if exact { "idiom" } else { "APPROXIMATE" } - ), - &local, - ); + let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local); if done(&local) { return local.map(|(shader, _)| shader); } } } if idiom(p, st) == exact { - let local = - lower::with_local_waves(|| emit_program(c, native, p, st, io, res, mesh)); - report( - if exact { - "local waves (idiom)" - } else { - "local waves (APPROXIMATE)" - }, - &local, - ); + let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local); if done(&local) { return local.map(|(shader, _)| shader); } @@ -521,20 +447,14 @@ pub fn emit_with( if !strict { for (name, f) in &forms { if let Some((p, st, io, res)) = f { - let local = lower::with_local_waves_any(|| { - emit_program(c, native, p, st, io, res, mesh) - }); - report( - &format!("local waves (APPROXIMATE, any mask), {name}"), - &local, - ); + let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); + report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local); if done(&local) { return local.map(|(shader, _)| shader); } } } - let local = - lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res, mesh)); + let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); report("local waves (APPROXIMATE, any mask)", &local); if done(&local) { return local.map(|(shader, _)| shader); @@ -554,7 +474,7 @@ pub fn emit_with( let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some()); match again { Ok(_) => again, - Err(_) => emit_program(c, native, p, st, io, res, mesh), + Err(_) => emit_program(c, native, p, st, io, res), } } other => other, @@ -573,7 +493,7 @@ pub fn emit_with( let st = structure::structure(&p)?; let io = io::raise(&p, native)?; let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - emit_program(c, native, &p, &st, &io, &res, mesh).map(|(shader, _)| shader) + emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader) } /// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane @@ -611,7 +531,7 @@ fn widen( let io = io::raise(p, native)?; let res = resource::track(p, &native.layout, native.stage, Some(&st))?; lower::take_needs(); - let r = emit_program(c, native, p, &st, &io, &res, MeshMode::Native); + let r = emit_program(c, native, p, &st, &io, &res); let needs = lower::take_needs(); // (or translated for 64-lane waves still: shared memory read and written where not // every lane runs, whose blocks the lowering names too) @@ -631,10 +551,7 @@ fn widen( .collect(); if more.is_empty() { if why { - eprintln!( - "WAVE64-WIDE stopped with {} branches wave-wide: a branch around it cannot be", - wide.len() - ); + eprintln!("WAVE64-WIDE stopped with {} branches wave-wide: a branch around it cannot be", wide.len()); } return r; } @@ -650,7 +567,6 @@ fn emit_program( st: &structure::Structured, io: &io::Io, res: &resource::Resources, - mesh: MeshMode, ) -> Result<(HostShader, Option), ShaderError> { let sig = |fourcc| -> Result, ShaderError> { match c.part(fourcc) { @@ -661,22 +577,11 @@ fn emit_program( let pixel = native.stage == HwStage::Ps; let mut inputs = sig(FourCC::ISG1)?; let mut outputs = sig(FourCC::OSG1)?; - // Interpolation as the console container's PSV0 declares it, falling back - // to DXC's defaults when no PSV0 is present; pixel inputs that are read - // also get the mode their barycentrics say. - let psv_modes = c - .part(FourCC::PSV0) - .and_then(|p| psv_interps(p.data, pixel)); + // Interpolation as DXC declares it by default; pixel inputs that are + // read get the mode their barycentrics say. let interpolated = if pixel { &mut inputs } else { &mut outputs }; for e in interpolated { - let from_psv = psv_modes.as_ref().and_then(|m| { - let key = match e.row { - Some(r) => (true, r, e.col, 0), - None => (false, 0, 0, e.kind), - }; - m.get(&key).copied().filter(|&mode| mode != 0) - }); - e.interp = from_psv.unwrap_or(match (e.kind, e.comp) { + e.interp = match (e.kind, e.comp) { (3, _) => 4, // Constant, as DXC declares it (the AMD compiler crashed on a // front face without a mode). @@ -686,15 +591,13 @@ fn emit_program( (0 | 6 | 7, 9) => 2, (0, _) => 1, _ => 0, - }); + }; } // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL // wants the position centroid (or per sample), as DXC declares it then. if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) { for e in inputs.iter_mut().filter(|e| e.kind == 3) { - if !matches!(e.interp, 5 | 7) { - e.interp = 5; - } + e.interp = 5; } } // Per-primitive outputs are constant. The console never exports a @@ -709,7 +612,7 @@ fn emit_program( // primitives) (the code divides by that); the thread count is in PSV0 // from runtime info version 2 on. // shortcut: older containers fall back to the group's lane count, right - // when the HLSL group fills its waves (Grand Theft Auto VI's do). + // when the HLSL group fills its waves (the title's do). let mesh_stride = match &native.io { crate::native::StageIo::Ms(ms) => { let psv = c.part(FourCC::PSV0).map(|p| p.data); @@ -732,96 +635,33 @@ fn emit_program( outputs, prims, mesh_stride, - crumbs: breadcrumbs().then(|| breadcrumb_slot(&c.digest)), - emulate_mesh: native.stage == HwStage::Ms && mesh == MeshMode::Emulate, })?; let wave_size = l.wave_size; let shader = HostShader { stage: native.stage, dxil: l.dxil, user_data: l.user_data, - static_samplers: build_static_samplers(&l.samplers, &l.cmp_samplers), + static_samplers: l + .samplers + .iter() + .enumerate() + .map(|(n, &w)| { + let mut s = StaticSampler::from_words(w); + if l.cmp_samplers >> n & 1 != 0 { + s.filter |= 0x80; + } + s + }) + .collect(), samplers: l.samplers, root_cbvs: l.root_cbvs, root_srvs: l.root_srvs, - address_map: l.address_map, - descriptor_words: l.descriptor_words, root_uavs: l.root_uavs, root_indexed_views: res.root_indexed_views.clone(), - mesh_emu: l.mesh_emu, }; Ok((shader, wave_size)) } -fn build_static_samplers(samplers: &[[u32; 4]], cmp_samplers: &[bool]) -> Vec { - samplers - .iter() - .zip(cmp_samplers) - .map(|(&w, &cmp)| { - let mut s = StaticSampler::from_words(w); - if cmp { - // Comparison overrides the 2-bit D3D12_FILTER_REDUCTION_TYPE - // field (bits 7..8), rather than ORing onto MINIMUM (0x100 -> MAXIMUM). - s.filter = (s.filter & !0x180) | 0x80; - } - s - }) - .collect() -} - -/// Per-element interpolation modes from a console container's `PSV0` part, -/// keyed by `(allocated, row, col, unallocated_kind)`. -fn psv_interps( - d: &[u8], - inputs: bool, -) -> Option> { - use crate::dxbc::u32_at; - let info_sz = u32_at(d, 0).ok()? as usize; - if info_sz < 36 || 4 + info_sz > d.len() { - return None; - } - let in_el = usize::from(*d.get(4 + 28)?); - let out_el = usize::from(*d.get(4 + 29)?); - let mut pos = 4 + info_sz; - let res_cnt = u32_at(d, pos).ok()? as usize; - pos += 4; - if res_cnt > 0 { - let res_sz = u32_at(d, pos).ok()? as usize; - pos = pos - .checked_add(4)? - .checked_add(res_cnt.checked_mul(res_sz)?)?; - } - let str_len = u32_at(d, pos).ok()? as usize; - pos = pos.checked_add(4)?.checked_add(str_len)?; - let idx_cnt = u32_at(d, pos).ok()? as usize; - pos = pos.checked_add(4)?.checked_add(idx_cnt.checked_mul(4)?)?; - if pos >= d.len() { - return Some(std::collections::HashMap::new()); - } - let el_sz = u32_at(d, pos).ok()? as usize; - pos += 4; - if el_sz < 14 { - return None; - } - let (start, count) = if inputs { (0, in_el) } else { (in_el, out_el) }; - let end = start.checked_add(count)?; - if pos.checked_add(end.checked_mul(el_sz)?)? > d.len() { - return None; - } - let mut out = std::collections::HashMap::with_capacity(count); - for k in start..end { - let e = &d[pos + k * el_sz..pos + (k + 1) * el_sz]; - let alloc = e[10] >> 6 & 1 != 0; - let key = if alloc { - (true, u32::from(e[9]), (e[10] >> 4) & 3, 0) - } else { - (false, 0, 0, e[11]) - }; - out.insert(key, e[13]); - } - Some(out) -} - /// The rows of an `ISG1`/`OSG1` part. fn signature(part: &[u8]) -> Result, ShaderError> { use crate::dxbc::u32_at; @@ -914,94 +754,6 @@ fn signature(part: &[u8]) -> Result, ShaderError> { Ok(out) } -/// A pixel shader for debug views (`VICTORY_DEBUG_PS` in the GPU crate): -/// colours each pixel by the slope of its surface, from the screen-space -/// derivatives of its depth (`SV_Position.z`), written to all `targets` -/// colour targets. It reads nothing of the title's, so a draw's geometry -/// shows whether or not its own pixel shader translates: a check that the -/// vertex and mesh stages place what they draw where it belongs. -pub fn debug_ps(targets: u32) -> HostShader { - use bitcode::{Attr, Bin, Term}; - use container::SigElement; - let mut s = shader::Shader::new(true); - let b = s.entry; - let undef = s.m.undef(s.t.i32); - let load = |s: &mut shader::Shader, col: u8| { - let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), undef]; - s.op(b, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args) - }; - let z = load(&mut s, 2); - let unary = |s: &mut shader::Shader, op: u32, v| { - s.op(b, "unary.f32", Attr::ReadNone, s.t.f32, op, &[v]) - }; - // DerivCoarseX, DerivCoarseY: depth changes slowly, so scale it up. - let (dx, dy) = (unary(&mut s, 83, z), unary(&mut s, 84, z)); - let k = s.m.f32((-4096.0f32).to_bits()); - let nx = s.m.bin(b, Bin::Mul, dx, k); - let ny = s.m.bin(b, Bin::Mul, dy, k); - let one = s.m.f32(1.0f32.to_bits()); - let half = s.m.f32(0.5f32.to_bits()); - let xx = s.m.bin(b, Bin::Mul, nx, nx); - let yy = s.m.bin(b, Bin::Mul, ny, ny); - let sum = s.m.bin(b, Bin::Add, xx, yy); - let sum = s.m.bin(b, Bin::Add, sum, one); - let len = unary(&mut s, 24, sum); // Sqrt - let colour = |s: &mut shader::Shader, v| { - let n = s.m.bin(b, Bin::SDiv, v, len); // fdiv on floats - let n = s.m.bin(b, Bin::Mul, n, half); - s.m.bin(b, Bin::Add, n, half) - }; - let rgb = [colour(&mut s, nx), colour(&mut s, ny), colour(&mut s, one)]; - let targets = targets.clamp(1, 8); - for t in 0..targets { - for (col, v) in rgb.iter().copied().chain([one]).enumerate() { - let args = [s.m.i32(t), s.m.i32(0), s.m.i8(col as u8), v]; - s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); - } - } - s.inputs = vec![SigElement { - name: "SV_Position".into(), - index: 0, - kind: 3, - comp: 9, - interp: 4, - row: Some(0), - col: 0, - cols: 4, - usage: 0b0100, - half: false, - }]; - s.outputs = (0..targets) - .map(|t| SigElement { - name: "SV_Target".into(), - index: t, - kind: 16, - comp: 9, - interp: 0, - row: Some(t), - col: 0, - cols: 4, - usage: 0b1111, - half: false, - }) - .collect(); - s.m.terminate(b, Term::Ret); - HostShader { - stage: HwStage::Ps, - dxil: s.finish(), - user_data: Vec::new(), - samplers: Vec::new(), - static_samplers: Vec::new(), - root_cbvs: Vec::new(), - root_srvs: Vec::new(), - address_map: false, - descriptor_words: false, - root_uavs: Vec::new(), - root_indexed_views: Vec::new(), - mesh_emu: None, - } -} - #[cfg(test)] mod tests { #[cfg(windows)] @@ -1009,6 +761,17 @@ mod tests { use super::lower::LOOP_LIMIT; use super::parse_loop_limit; + #[test] + fn the_clean_up_switch_parses_or_runs_every_pass() { + let all = super::bitcode::opt::ALL; + assert_eq!(parse_shader_opt(None), all); + assert_eq!(parse_shader_opt(Some("0")), 0); + assert_eq!(parse_shader_opt(Some(" 1 ")), 1); + assert_eq!(parse_shader_opt(Some("0x1")), 1); + assert_eq!(parse_shader_opt(Some("0xffffffff")), all); + assert_eq!(parse_shader_opt(Some("on")), all); + } + #[test] fn the_loop_limit_switch_parses_or_falls_back() { assert_eq!(parse_loop_limit(None), LOOP_LIMIT); @@ -1047,7 +810,6 @@ mod tests { used: vec![], io: StageIo::Ps { inputs: vec![], - rsrc2: 0, input_addr: 0, db_shader_control: 0, patches: vec![], @@ -1209,10 +971,10 @@ mod tests { /// A carry-in reading a join of compares after a divergent branch. A /// lane that skipped the inner compare has VCC clear there (VOPC clears - /// inactive lanes), not the first compare's bit; the merged mask - /// tracking joins the compares per lane, so the carry-in lowers. + /// inactive lanes), not the first compare's bit, so the join is no + /// per-lane phi: lowering refuses it. #[test] - fn a_carry_in_from_a_divergent_join_lowers() { + fn a_carry_in_from_a_divergent_join_is_refused() { let body = [ 0x7E04_028B, // v_mov_b32 v2, 11 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 @@ -1222,7 +984,8 @@ mod tests { 0x88FE_027E, // s_or_b64 exec, exec, s[2:3] 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc ]; - stores_v1(&body).expect("the joined mask's carry-in lowers"); + let e = stores_v1(&body).unwrap_err().to_string(); + assert!(e.contains("a carry-in from an untracked mask"), "{e}"); } /// A pixel shader writing a constant colour. @@ -1255,18 +1018,6 @@ mod tests { s.finish() } - #[test] - #[cfg(windows)] - fn debug_pixel_shader_makes_a_pipeline() { - let Ok(host) = super::host::Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; - }; - let ps = super::debug_ps(3); - let vs = super::host::stub_vs(&ps).unwrap(); - host.pipeline(&vs, &ps).unwrap(); - } - #[test] #[cfg(windows)] fn stub_pipeline_is_created() { @@ -1282,11 +1033,8 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), - address_map: false, - descriptor_words: false, root_uavs: Vec::new(), root_indexed_views: Vec::new(), - mesh_emu: None, }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -1297,11 +1045,8 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), - address_map: false, - descriptor_words: false, root_uavs: Vec::new(), root_indexed_views: Vec::new(), - mesh_emu: None, }) }; let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); @@ -1313,16 +1058,6 @@ mod tests { v.validate(&mut vs.dxil.clone()).unwrap(); } host.pipeline(&vs, &ps).unwrap(); - // vkd3d-proton (Wine, Proton) does not check the container hash. - // SAFETY: plain lookups in ntdll, always loaded. - let wine = unsafe { - use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; - let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); - !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() - }; - if wine { - return; - } // The runtime checks the container hash: no hash or a wrong one is // refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass // value; ours works with older ones too.) @@ -1383,7 +1118,6 @@ mod tests { pack2: false, row2: 0, }], - rsrc2: 0, input_addr, db_shader_control: 0, patches: vec![], @@ -1409,7 +1143,8 @@ mod tests { let c = super::Container::parse(&bytes).unwrap(); let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); let st = crate::structure::structure(&p).unwrap(); - let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let res = + crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); let io = crate::io::raise(&p, &native).unwrap(); let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); // dxil.dll, where there is one, checks PSV0 against the module. @@ -1429,49 +1164,6 @@ mod tests { assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency"); } - /// A system value whose console signature used non-canonical casing (such - /// as `SV_TARGET`) must be written with DXIL's canonical name (`SV_Target`) - /// in `ISG1`/`OSG1` so `dxil.dll` validation accepts the container part. - #[test] - #[cfg(windows)] - fn non_canonical_system_value_name_validates() { - let mut s = super::shader::Shader::new(true); - s.outputs.push(SigElement { - name: "SV_TARGET".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 0xf, - half: false, - }); - let zero = s.m.f32(0); - let id = s.m.i32(0); - let row = s.m.i32(0); - let void = s.t.void; - for ch in 0..4u8 { - let c = s.m.i8(ch); - s.op( - s.entry, - "storeOutput.f32", - super::bitcode::Attr::NoUnwind, - void, - 5, - &[id, row, c, zero], - ); - } - s.m.terminate(s.entry, super::bitcode::Term::Ret); - let mut c = s.finish(); - let path = super::validator::Validator::default_path(); - let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else { - return; - }; - v.validate(&mut c).unwrap(); - } - /// A pixel shader reading channel z of an input whose element starts at /// w. Looking the channel up subtracted the element's first channel /// before checking the channel lies in it, so in a build with overflow @@ -1498,7 +1190,6 @@ mod tests { pack2: false, row2: 0, }], - rsrc2: 0, input_addr: 0, db_shader_control: 0, patches: vec![], @@ -1528,423 +1219,6 @@ mod tests { let _ = super::emit(&c, &native, &p, &st, &io, &res); } - fn lower_immediate_sampler_cs(words: &[u32]) -> super::HostShader { - let table = crate::native::RootParam { - root: crate::native::RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 0, - slot: 0, - }; - let range = |kind, table_offset_dwords, dwords| crate::native::UsedResource { - kind, - root: crate::native::RootType::Table, - table_offset_dwords, - lower_bound: 0, - stride: 0, - dwords, - user_data: 0, - slot: 0, - }; - let native = super::NativeProgram { - stage: super::HwStage::Cs, - wave64: false, - vgprs: 32, - layout: vec![table], - used: vec![ - range(crate::native::ResourceType::Srv, 0, 8), - range(crate::native::ResourceType::Uav, 8, 4), - ], - io: crate::native::StageIo::Cs(crate::native::ComputeIo { - rsrc2: 2 << 1, - threads: [1, 1, 1], - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let p = crate::ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - let st = crate::structure::structure(&p).expect("structure"); - let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)) - .expect("resource::track"); - let io = crate::io::raise(&p, &native).expect("io::raise"); - let l = super::lower::lower(&super::lower::Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: Vec::new(), - outputs: Vec::new(), - prims: Vec::new(), - mesh_stride: 0, - crumbs: None, - emulate_mesh: false, - }) - .expect("lower"); - let shader = super::HostShader { - stage: native.stage, - dxil: l.dxil, - user_data: l.user_data, - static_samplers: super::build_static_samplers(&l.samplers, &l.cmp_samplers), - samplers: l.samplers, - root_cbvs: l.root_cbvs, - root_srvs: l.root_srvs, - address_map: l.address_map, - descriptor_words: l.descriptor_words, - root_uavs: l.root_uavs, - root_indexed_views: Vec::new(), - mesh_emu: None, - }; - #[cfg(windows)] - if let Ok(mut v) = super::validator::Validator::load( - super::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut shader.dxil.clone()) - .expect("DXIL validation failed"); - } - shader - } - - fn dual_use_sampler_program(sampler: [u32; 4], cmp_first: bool) -> Vec { - let mut words = vec![ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF40C_0302, - 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 - 0xF408_0A02, - 0xFA00_0020, // s_load_dwordx4 s[40:43], s[4:5], 0x20 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - ]; - for (i, w) in sampler.into_iter().enumerate() { - words.push(0xBE88_03FF | ((i as u32) << 16)); // s_mov_b32 s(8+i), lit32 - words.push(w); - } - let v_mov_lit = |dst: u32, lit: f32, out: &mut Vec| { - out.push(0x7E00_02FF | (dst << 17)); - out.push(lit.to_bits()); - }; - v_mov_lit(1, 0.25, &mut words); // ref1 = 0.25 (<= 0.5 -> 1.0) - v_mov_lit(2, 0.5, &mut words); - v_mov_lit(3, 0.5, &mut words); - v_mov_lit(4, 0.75, &mut words); // ref2 = 0.75 (> 0.5 -> 0.0) - v_mov_lit(5, 0.5, &mut words); - v_mov_lit(6, 0.5, &mut words); - words.push(0x7E20_0280); // v_mov_b32 v16, 0 - - let std_sample = [0xF09C_0108, 0x0043_0C02]; // image_sample_lz v12, v[2:3], s[12:19], s[8:11] - let cmp_sample_1 = [0xF0BC_0108, 0x0043_0D01]; // image_sample_c_lz v13, v[1:3], s[12:19], s[8:11] - let cmp_sample_2 = [0xF0BC_0108, 0x0043_0E04]; // image_sample_c_lz v14, v[4:6], s[12:19], s[8:11] - if cmp_first { - words.extend(cmp_sample_1); - words.extend(cmp_sample_2); - words.extend(std_sample); - } else { - words.extend(std_sample); - words.extend(cmp_sample_1); - words.extend(cmp_sample_2); - } - words.extend([ - 0xBF8C_3F70, // s_waitcnt vmcnt(0) - 0xE070_1000, - 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen - 0xE070_1004, - 0x800A_0D10, // buffer_store_dword v13, v16, s[40:43], 0 offen offset:4 - 0xE070_1008, - 0x800A_0E10, // buffer_store_dword v14, v16, s[40:43], 0 offen offset:8 - 0xBF81_0000, // s_endpgm - ]); - words - } - - #[test] - fn constant_sampler_used_with_and_without_comparison_splits_into_two_static_samplers() { - // Point clamp, comparison LESS_EQUAL (4). - let sampler = [0x3092u32, 0x00FF_F000, 0x0000_0000, 0x0000_0000]; - for cmp_first in [false, true] { - let shader = lower_immediate_sampler_cs(&dual_use_sampler_program(sampler, cmp_first)); - assert_eq!(shader.samplers, vec![sampler, sampler]); - assert_eq!(shader.static_samplers.len(), 2); - let filters: Vec = shader.static_samplers.iter().map(|s| s.filter).collect(); - let expected = if cmp_first { - vec![0x80, 0x00] - } else { - vec![0x00, 0x80] - }; - assert_eq!(filters, expected, "cmp_first={cmp_first}"); - - #[cfg(all(windows, feature = "host"))] - { - use super::host::{Dispatch, Host, Root, View}; - let _one = super::valu_tests::ONE_AT_A_TIME - .lock() - .unwrap_or_else(|e| e.into_inner()); - // D3D12 leaves `SHADER_SAMPLE_COMPARISON` optional for RGBA32F on - // hardware; WARP implements it everywhere. - if let Ok(host) = Host::new(true) { - let texel = [[0.5f32, 0.0, 0.0, 1.0]]; - let views = [View::Texture(1, 1, &texel), View::RawUav(3)]; - let (root, pso) = host - .compute_pipeline(&shader) - .unwrap_or_else(|e| panic!("warp: compute_pipeline: {e}")); - let words = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![(0, Root::Constants(vec![0]))], - views: &views, - samplers: &[], - groups: [1, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("warp: dispatch: {e}")); - let got: Vec = words[0].iter().copied().map(f32::from_bits).collect(); - assert_eq!(got, vec![0.5, 1.0, 0.0], "warp cmp_first={cmp_first}"); - } - } - } - - // A MINIMUM reduction sampler (0x100) also used with comparison must - // become COMPARISON (0x80), not MAXIMUM (0x180). - let min_sampler = [0x2000_3092u32, 0x00FF_F000, 0x0000_0000, 0x0000_0000]; - let shader = lower_immediate_sampler_cs(&dual_use_sampler_program(min_sampler, false)); - let filters: Vec = shader.static_samplers.iter().map(|s| s.filter).collect(); - assert_eq!(filters, vec![0x100, 0x80]); - } - - #[test] - fn more_than_64_immediate_samplers_do_not_overflow() { - let mut words = vec![ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF40C_0302, - 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 - 0xF408_0A02, - 0xFA00_0020, // s_load_dwordx4 s[40:43], s[4:5], 0x20 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0x7E02_0280, // v_mov_b32 v1, 0 - 0x7E04_0280, // v_mov_b32 v2, 0 - 0x7E06_0280, // v_mov_b32 v3, 0 - 0x7E20_0280, // v_mov_b32 v16, 0 - ]; - for i in 0..66u32 { - // Vary MaxLOD across bits 12..23 cleanly without colliding with 1-bits. - let sampler = [0x3092u32, (i + 1) << 12, 0x0000_0000, 0x0000_0000]; - for (j, w) in sampler.into_iter().enumerate() { - words.push(0xBE88_03FF | ((j as u32) << 16)); - words.push(w); - } - if !i.is_multiple_of(2) { - words.extend([0xF0BC_0108, 0x0043_0C01]); // image_sample_c_lz v12, v[1:3], s[12:19], s[8:11] - } else { - words.extend([0xF09C_0108, 0x0043_0C02]); // image_sample_lz v12, v[2:3], s[12:19], s[8:11] - } - words.extend([ - 0xBF8C_3F70, // s_waitcnt vmcnt(0) - 0xE070_1000 | ((i * 4) & 0x0FFF), // buffer_store_dword v12, v16, s[40:43], 0 offen offset:... - 0x800A_0C10, - ]); - } - words.push(0xBF81_0000); // s_endpgm - - let shader = lower_immediate_sampler_cs(&words); - assert_eq!(shader.samplers.len(), 66); - assert_eq!(shader.static_samplers.len(), 66); - for (i, s) in shader.static_samplers.iter().enumerate() { - let expected = if !i.is_multiple_of(2) { 0x80 } else { 0x00 }; - assert_eq!(s.filter & 0x180, expected, "sampler {i}"); - } - } - - #[test] - fn pixel_reads_of_uninitialized_sgprs_read_as_zero() { - let try_emit = |rsrc2: u32, sgpr: u32| { - // v_mov_b32 v0, s; exp mrt0, v0, v0, v0, v0 done vm; s_endpgm - let words = [0x7E00_0200u32 | sgpr, 0xF800_180F, 0x0000_0000, 0xBF81_0000]; - let native = super::NativeProgram { - stage: super::HwStage::Ps, - wave64: false, - vgprs: 2, - layout: vec![], - used: vec![], - io: crate::native::StageIo::Ps { - inputs: vec![], - rsrc2, - input_addr: 0, - db_shader_control: 0, - patches: vec![], - }, - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let osg1 = super::container::signature( - &[SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 15, - half: false, - }], - false, - ); - let bytes = crate::dxbc::build(&[(super::FourCC::OSG1, &osg1)]); - let c = super::Container::parse(&bytes).unwrap(); - let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let st = crate::structure::structure(&p).unwrap(); - let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = crate::io::raise(&p, &native).unwrap(); - super::emit(&c, &native, &p, &st, &io, &res) - }; - - // 2 user SGPRs (s0..=s1) + prim_mask (s2) -> initialized_sgprs = 3. - let rsrc2 = 2 << 1; - // s2 is hardware-initialized (prim_mask) and must still be refused. - assert!(matches!( - try_emit(rsrc2, 2), - Err(crate::ShaderError::Unsupported { - what: "a hardware SGPR input", - .. - }) - )); - // s3 is uninitialized on entry and reads as zero, passing DXIL validation. - let _out = try_emit(rsrc2, 3).unwrap(); - #[cfg(windows)] - if let Ok(mut v) = super::validator::Validator::load( - super::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut _out.dxil.clone()).unwrap(); - } - // Enabling SCRATCH_EN (bit 0) initializes s3 (scratch wave offset), so - // s3 is refused again while s4 reads as zero. - assert!(matches!( - try_emit(rsrc2 | 1, 3), - Err(crate::ShaderError::Unsupported { - what: "a hardware SGPR input", - .. - }) - )); - let _out = try_emit(rsrc2 | 1, 4).unwrap(); - #[cfg(windows)] - if let Ok(mut v) = super::validator::Validator::load( - super::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut _out.dxil.clone()).unwrap(); - } - } - - #[test] - fn console_psv_interpolation_modes_are_preserved_for_copacked_inputs() { - // A float input co-packed in row 0 alongside a uint input must keep - // the console PSV0's Constant (1) mode instead of defaulting to Linear - // (2), which DXIL validator 1.6 rejects when mixed in one register. - let words = [ - 0xC80E_0000u32, // v_interp_mov_f32 v0, p0, attr0.x - 0xF800_180F, - 0x0000_0000, // exp mrt0, v0, v0, v0, v0 done vm - 0xBF81_0000, - ]; - let native = super::NativeProgram { - stage: super::HwStage::Ps, - wave64: false, - vgprs: 4, - layout: vec![], - used: vec![], - io: crate::native::StageIo::Ps { - inputs: vec![crate::native::PsInput { - usage: crate::native::Usage::Generic, - row: 0, - mask: 0b11, - attr: 0, - flat: true, - fp16: false, - pack2: false, - row2: 0, - }], - rsrc2: 0, - input_addr: 0, - db_shader_control: 0, - patches: vec![], - }, - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let f_flat = SigElement { - name: "TEXCOORD".into(), - index: 0, - kind: 0, - comp: 9, - interp: 1, - row: Some(0), - col: 0, - cols: 1, - usage: 1, - half: false, - }; - let u_flat = SigElement { - name: "TEXCOORD".into(), - index: 1, - kind: 0, - comp: 5, - interp: 1, - row: Some(0), - col: 1, - cols: 1, - usage: 0, - half: false, - }; - let target = SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 0xF, - half: false, - }; - let isg1 = super::container::signature(&[f_flat.clone(), u_flat.clone()], true); - let osg1 = super::container::signature(std::slice::from_ref(&target), false); - let psv0 = super::container::psv(&super::container::Psv { - stage: 0, - flag: false, - inputs: &[f_flat, u_flat], - outputs: &[target], - prims: &[], - mesh: None, - bindings: &[], - threads: [0; 3], - wave_size: None, - validator18: false, - geometry: None, - }); - let bytes = crate::dxbc::build(&[ - (super::FourCC::ISG1, &isg1), - (super::FourCC::OSG1, &osg1), - (super::FourCC::PSV0, &psv0), - ]); - let c = super::Container::parse(&bytes).unwrap(); - let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let st = crate::structure::structure(&p).unwrap(); - let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = crate::io::raise(&p, &native).unwrap(); - let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); - let host = super::Container::parse(&out.dxil).unwrap(); - let modes = super::psv_interps(host.part(super::FourCC::PSV0).unwrap().data, true).unwrap(); - assert_eq!(modes.get(&(true, 0, 0, 0)), Some(&1)); - assert_eq!(modes.get(&(true, 0, 1, 0)), Some(&1)); - #[cfg(windows)] - if let Ok(mut v) = super::validator::Validator::load( - super::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut out.dxil.clone()).unwrap(); - } - } - #[test] fn valu_div_f32_sequence_executes_on_gpu() { let words: &[u32] = &[ @@ -2031,8 +1305,7 @@ mod tests { let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); let io = crate::io::raise(&p, &native).unwrap(); let st = crate::structure::structure(&p).unwrap(); - // Everything below runs only under Windows (validator + host dispatch). - let _l = super::lower::lower(&super::lower::Parts { + let l = super::lower::lower(&super::lower::Parts { native: &native, p: &p, st: &st, @@ -2042,12 +1315,12 @@ mod tests { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - crumbs: None, - emulate_mesh: false, }) .unwrap(); #[cfg(windows)] - let mut dxil = _l.dxil; + let mut dxil = l.dxil; + #[cfg(not(windows))] + let _ = l.dxil; #[cfg(windows)] if let Ok(mut v) = super::validator::Validator::load( super::validator::Validator::default_path().as_deref(), @@ -2059,16 +1332,13 @@ mod tests { let cs = super::HostShader { stage: super::HwStage::Cs, dxil, - user_data: _l.user_data, + user_data: l.user_data, samplers: Vec::new(), static_samplers: Vec::new(), - root_cbvs: _l.root_cbvs, - root_srvs: _l.root_srvs, - address_map: false, - descriptor_words: false, - root_uavs: _l.root_uavs, + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + root_uavs: l.root_uavs, root_indexed_views: Vec::new(), - mesh_emu: None, }; let (root, pso) = host.compute_pipeline(&cs).unwrap(); let inputs: Vec = [ @@ -2260,7 +1530,6 @@ mod barycentric_tests { pack2: false, row2: 0, }], - rsrc2: 0, input_addr, db_shader_control: 0, patches: vec![], @@ -2476,84 +1745,4 @@ mod barycentric_tests { let words = [0xC812_0000, e0, e1, S_ENDPGM]; assert!(pixel(&words, PERSP_CENTER).is_err()); } - - /// input_addr + a TEXCOORD row: PSV0 carries the interpolation modes of - /// each attribute row (wave-4 #1043 behaviour on the merged pixel()). - #[test] - fn input_addr_psv0_modes() { - let [e0, e1] = exp_mrt0(2); - let words = [v_add_f32(2, 0, 1), e0, e1, 0xBF81_0000]; - // The console's PSV0 declares the attribute row's modes; the emitted - // PSV0 keeps them for both columns. - let native = NativeProgram { - stage: HwStage::Ps, - wave64: false, - vgprs: 8, - layout: vec![], - used: vec![], - io: StageIo::Ps { - inputs: vec![PsInput { - usage: Usage::Generic, - row: 0, - mask: 0b11, - attr: 0, - flat: true, - fp16: false, - pack2: false, - row2: 0, - }], - rsrc2: 0, - input_addr: PERSP_CENTER, - db_shader_control: 0, - patches: vec![], - }, - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let el = |comp, col: u8| SigElement { - name: "TEXCOORD".into(), - index: u32::from(col), - kind: 0, - comp, - interp: 1, - row: Some(0), - col, - cols: 1, - usage: 0, - half: false, - }; - let inputs = [el(9, 0), el(5, 1)]; - let mut target = element("SV_Target", 16, 0); - target.usage = 15; - let isg1 = container::signature(&inputs, true); - let osg1 = container::signature(&[target.clone()], false); - let psv0 = container::psv(&container::Psv { - stage: 0, - flag: false, - inputs: &inputs, - outputs: &[target], - prims: &[], - mesh: None, - geometry: None, - bindings: &[], - threads: [0; 3], - wave_size: None, - validator18: false, - }); - let bytes = crate::dxbc::build(&[ - (FourCC::ISG1, &isg1), - (FourCC::OSG1, &osg1), - (FourCC::PSV0, &psv0), - ]); - let c = Container::parse(&bytes).unwrap(); - let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = crate::io::raise(&p, &native).unwrap(); - let shader = emit(&c, &native, &p, &st, &io, &res).unwrap(); - let host = Container::parse(&shader.dxil).unwrap(); - let modes = super::psv_interps(host.part(FourCC::PSV0).unwrap().data, true).unwrap(); - assert_eq!(modes.get(&(true, 0, 0, 0)), Some(&1)); - assert_eq!(modes.get(&(true, 0, 1, 0)), Some(&1)); - validate(&shader); - } } diff --git a/crates/victory-shader/src/emit/mtbuf_tests.rs b/crates/victory-shader/src/emit/mtbuf_tests.rs deleted file mode 100644 index 3ae227e..0000000 --- a/crates/victory-shader/src/emit/mtbuf_tests.rs +++ /dev/null @@ -1,178 +0,0 @@ -//! Synthetic normalized MTBUF loads. gfx1036 measurements in #1060 found -//! correctly rounded results for all twenty formats, including packed fields. - -use super::{HostShader, emit}; -use crate::native::{ - ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, -}; -use crate::{Container, FourCC, io, ir, resource, structure}; - -// UNORM format and field widths from low to high. The next format is SNORM. -const FORMATS: &[(u8, &[u32])] = &[ - (1, &[8]), - (7, &[16]), - (14, &[8, 8]), - (23, &[16, 16]), - (30, &[11, 11, 10]), - (37, &[10, 11, 11]), - (44, &[2, 10, 10, 10]), - (50, &[10, 10, 10, 2]), - (56, &[8, 8, 8, 8]), - (65, &[16, 16, 16, 16]), -]; - -/// Each thread reads one 16-byte row of a raw SRV, then writes its four -/// converted dwords to the corresponding row of a separate raw UAV. -fn load_shader(format: u8) -> HostShader { - let words = [ - 0x8F02_8601, // s_lshl_b32 s2, s1, 6 (group ID x times 64) - 0x4A00_0002, // v_add_nc_u32 v0, s2, v0 (plus thread ID x) - 0x3400_0084, // v_lshlrev_b32 v0, 4, v0 (byte offset) - 0xBE81_0380, // s_mov_b32 s1, 0 (high half of table address) - 0xF408_0200, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[0:1], 0 - 0xF408_0300, - 0xFA00_0020, // s_load_dwordx4 s[12:15], s[0:1], 32 - 0xE803_1000 | (u32::from(format) << 19), - 0x8002_0100, // tbuffer_load_format_xyzw v[1:4], v0, s[8:11], 0 offen - 0xE078_1000, - 0x8003_0100, // buffer_store_dwordx4 v[1:4], v0, s[12:15], 0 offen - 0xBF81_0000, // s_endpgm - ]; - let range = |kind, table_offset_dwords| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 0, - slot: 0, - }; - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 5, - layout: vec![RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 0, - slot: 0, - }], - used: vec![range(ResourceType::Srv, 0), range(ResourceType::Uav, 8)], - io: StageIo::Cs(ComputeIo { - rsrc2: 1 << 7 | 1 << 1, // group ID x and one user SGPR - threads: [64, 1, 1], - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let p = ir::build(&native.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 bytes = crate::dxbc::build(&[]); - let container = Container::parse(&bytes).unwrap(); - emit(&container, &native, &p, &st, &io, &res).unwrap() -} - -#[test] -fn normalized_mtbuf_loads_need_no_int64() { - for &(unorm, _) in FORMATS { - for format in [unorm, unorm + 1] { - let shader = load_shader(format); - let c = Container::parse(&shader.dxil).unwrap(); - let sfi0 = c.part(FourCC::SFI0).unwrap().data; - let flags = u64::from_le_bytes(sfi0.try_into().unwrap()); - assert_eq!(flags & 0x8000, 0, "format {format}, SFI0 {flags:#x}"); - #[cfg(windows)] - if let Ok(mut validator) = super::validator::Validator::load( - super::validator::Validator::default_path().as_deref(), - ) { - validator.validate(&mut shader.dxil.clone()).unwrap(); - } - } - } -} - -#[cfg(windows)] -#[test] -fn normalized_mtbuf_loads_round_every_field_value() { - use super::host::{Dispatch, Host, Root, Stride, View}; - let _one = super::valu_tests::ONE_AT_A_TIME - .lock() - .unwrap_or_else(|e| e.into_inner()); - let hosts: Vec<_> = [("hardware", false), ("warp", true)] - .into_iter() - .filter_map(|(name, warp)| Host::new(warp).ok().map(|h| (name, h))) - .collect(); - assert!(!hosts.is_empty(), "no SM 6.6 device"); - - for &(unorm, widths) in FORMATS { - let rows = 1u32 << widths.iter().max().unwrap(); - for signed in [false, true] { - let format = unorm + u8::from(signed); - let shader = load_shader(format); - let mut data = Vec::new(); - let mut expected = Vec::new(); - for row in 0..rows { - let mut packed = 0u64; - let mut shift = 0; - for (channel, &width) in widths.iter().enumerate() { - // Distinguish the channels and visit every field value. - let raw = (row + channel as u32 * 71) & ((1 << width) - 1); - packed |= u64::from(raw) << shift; - shift += width; - let max = (1i32 << (width - u32::from(signed))) - 1; - let k = if signed && raw > max as u32 { - raw as i32 - (1 << width) - } else { - raw as i32 - }; - let ratio = f64::from(k.max(-max)) / f64::from(max); - expected.push((ratio as f32).to_bits()); - } - data.extend([packed as u32, (packed >> 32) as u32, 0, 0]); - } - for (name, host) in &hosts { - let (root, pso) = host.compute_pipeline(&shader).unwrap(); - let out = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![( - 0, - Root::Constants(vec![0; shader.user_data_dwords() as usize]), - )], - views: &[ - View::Buffer { - data: &data, - stride: Stride::Raw, - }, - View::RawUav(4 * rows), - ], - samplers: &[], - groups: [rows / 64, 1, 1], - }, - ) - .unwrap(); - assert_eq!(out[0].len(), 4 * rows as usize, "{name}: format {format}"); - for (row, (got, want)) in out[0] - .as_chunks::<4>() - .0 - .iter() - .zip(expected.chunks_exact(widths.len())) - .enumerate() - { - assert_eq!( - &got[..widths.len()], - want, - "{name}: format {format}, row {row}" - ); - } - } - } - } -} diff --git a/crates/victory-shader/src/emit/own_bits.rs b/crates/victory-shader/src/emit/own_bits.rs index db8642b..64aaba8 100644 --- a/crates/victory-shader/src/emit/own_bits.rs +++ b/crates/victory-shader/src/emit/own_bits.rs @@ -173,9 +173,7 @@ fn effect(inst: &Inst) -> bool { || name.contains("store") || name.contains("atomic") || matches!(inst.fields, Fields::Ds { .. }) - && !(name.starts_with("ds_read") - || name.starts_with("ds_swizzle") - || name.contains("permute")) + && !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || name.contains("permute")) || matches!(name, "s_barrier" | "s_sendmsg" | "s_sendmsghalt") } @@ -278,9 +276,7 @@ impl Ctx<'_> { .into_iter() .flatten() .filter_map(|u| match *u { - User::Phi(b, k) if self.live.contains(&self.p.blocks[b].phis[k].value) => { - Some((b, k)) - } + User::Phi(b, k) if self.live.contains(&self.p.blocks[b].phis[k].value) => Some((b, k)), _ => None, }) .collect(); @@ -350,7 +346,6 @@ impl Ctx<'_> { /// One wave OR `t` of `x` over the lanes of `mask`, left by a section of block `sb`: the /// VGPR values its loop keeps alike, or where and why it is not such a loop. - #[allow(clippy::needless_range_loop)] fn site(&self, sb: usize, t: Value, x: Value, mask: Value) -> Result, (usize, Why)> { let p = self.p; let st = self.st; @@ -369,11 +364,9 @@ impl Ctx<'_> { // an unguarded copy let copy = |u: (usize, usize)| -> Option { let i = self.inst(u); - (matches!(i.name(), "v_mov_b32" | "s_mov_b32") - && args(i).len() == 1 - && st.guards[u.0][u.1].is_none()) - .then(|| result(i)) - .flatten() + (matches!(i.name(), "v_mov_b32" | "s_mov_b32") && args(i).len() == 1 && st.guards[u.0][u.1].is_none()) + .then(|| result(i)) + .flatten() }; let mut init = vec![t]; // (SCC, whether it is set when the OR is empty) @@ -381,10 +374,8 @@ impl Ctx<'_> { for u in self.readers(t) { let i = self.inst(u); let name = i.name(); - if matches!( - name, - "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32" - ) && other(i, t) == Some(Arg::K(0)) + if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32") + && other(i, t) == Some(Arg::K(0)) && zero.is_none() && let Some(scc) = i.write(Reg::Scc) { @@ -459,9 +450,7 @@ impl Ctx<'_> { } match (name, &args(i)[..]) { ("s_ff1_i32_b32", [Arg::Val(_)]) if idx.is_none() => idx = result(i), - ("s_xor_b32", _) | ("s_andn2_b32", [Arg::Val(_), Arg::Val(_)]) - if next.is_none() => - { + ("s_xor_b32", _) | ("s_andn2_b32", [Arg::Val(_), Arg::Val(_)]) if next.is_none() => { let bit = match (name, &args(i)[..]) { ("s_andn2_b32", [Arg::Val(c), Arg::Val(b)]) if *c == cur && *b != cur => *b, ("s_xor_b32", _) => match other(i, cur) { @@ -510,9 +499,7 @@ impl Ctx<'_> { }; let by_idx = shifted.is_some_and(|sh| { sh == idx - || made(sh).is_some_and(|(_, i)| { - i.name() == "s_and_b32" && other(i, idx) == Some(Arg::K(31)) - }) + || made(sh).is_some_and(|(_, i)| i.name() == "s_and_b32" && other(i, idx) == Some(Arg::K(31))) }); if !by_idx { return Err((head, SHAPE)); @@ -523,10 +510,8 @@ impl Ctx<'_> { for u in self.readers(nx) { let i = self.inst(u); let name = i.name(); - if matches!( - name, - "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32" - ) && other(i, nx) == Some(Arg::K(0)) + if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32") + && other(i, nx) == Some(Arg::K(0)) && let Some(scc) = i.write(Reg::Scc) { more.push((scc, name.contains("_lg_"))); @@ -553,11 +538,7 @@ impl Ctx<'_> { } } for (q, a) in p.blocks[h].preds.iter().zip(&phi.args) { - let ok = if lp[*q] { - nexts.contains(a) - } else { - init.contains(a) - }; + let ok = if lp[*q] { nexts.contains(a) } else { init.contains(a) }; if !ok { return Err((head, SHAPE)); } @@ -572,11 +553,7 @@ impl Ctx<'_> { continue; } let (u, set, clear) = self.branch(scc).ok_or((head, USED))?; - let (on, out) = if set_while_more { - (set, clear) - } else { - (clear, set) - }; + let (on, out) = if set_while_more { (set, clear) } else { (clear, set) }; if !lp[u.0] || !lp[on] || lp[out] { return Err((self.at(u), SHAPE)); } @@ -595,11 +572,7 @@ impl Ctx<'_> { } if !self.readers(scc).is_empty() { let (u, set, clear) = self.branch(scc).ok_or((here, USED))?; - let (none, some) = if set_when_empty { - (set, clear) - } else { - (clear, set) - }; + let (none, some) = if set_when_empty { (set, clear) } else { (clear, set) }; if none == some || lp[u.0] { return Err((self.at(u), SHAPE)); } @@ -628,10 +601,7 @@ impl Ctx<'_> { let mut tests: Vec<(Atom, usize, usize)> = Vec::new(); for u in self.readers(bit) { let i = self.inst(u); - if i.name() != "v_and_b32" - || other(i, bit) != Some(Arg::Val(x)) - || st.guards[u.0][u.1].is_some() - { + if i.name() != "v_and_b32" || other(i, bit) != Some(Arg::Val(x)) || st.guards[u.0][u.1].is_some() { continue; } let Some(y) = result(i) else { continue }; @@ -639,14 +609,8 @@ impl Ctx<'_> { let ci = self.inst(c); if matches!( ci.name(), - "v_cmp_ne_u32" - | "v_cmpx_ne_u32" - | "v_cmp_lg_u32" - | "v_cmpx_lg_u32" - | "v_cmp_ne_i32" - | "v_cmpx_ne_i32" - | "v_cmp_lg_i32" - | "v_cmpx_lg_i32" + "v_cmp_ne_u32" | "v_cmpx_ne_u32" | "v_cmp_lg_u32" | "v_cmpx_lg_u32" | "v_cmp_ne_i32" | "v_cmpx_ne_i32" + | "v_cmp_lg_i32" | "v_cmpx_lg_i32" ) && other(ci, y) == Some(Arg::K(0)) && lp[c.0] { @@ -670,8 +634,7 @@ impl Ctx<'_> { || lp[b] && st.guards[b][i].is_some_and(|g| { tests.iter().enumerate().any(|(j, &(a, tb, ti))| { - (b == tb && i > ti || b != tb && self.dominates(tb, b)) - && self.implied(g, a, &mut memo[j]) + (b == tb && i > ti || b != tb && self.dominates(tb, b)) && self.implied(g, a, &mut memo[j]) }) }) }; @@ -683,10 +646,7 @@ impl Ctx<'_> { } let u = (b, i); for &(reg, w) in &inst.writes { - if rem.contains(&w) - || is_mask(w) - || matches!(reg, Reg::S(c) if c == EXEC || c == EXEC + 1) - { + if rem.contains(&w) || is_mask(w) || matches!(reg, Reg::S(c) if c == EXEC || c == EXEC + 1) { continue; } for user in self.users.get(&w).into_iter().flatten() { @@ -714,9 +674,7 @@ impl Ctx<'_> { || name.contains("lane") || matches!(&inst.fields, Fields::Valu(v) if v.dpp.is_some()) || super::lower::reads_mask_as_data(st, inst) - || self.sections[b] - .iter() - .any(|(&s, sec)| i >= s && i <= sec.end); + || self.sections[b].iter().any(|(&s, sec)| i >= s && i <= sec.end); if cross { return Err((self.at(u), CROSS)); } @@ -742,9 +700,7 @@ impl Ctx<'_> { changed = false; for (&id, edges) in &st.phi_masks { if !dep.contains(&Atom::Phi(id)) - && edges - .iter() - .any(|&e| st.bools.support(e).iter().any(|a| dep.contains(a))) + && edges.iter().any(|&e| st.bools.support(e).iter().any(|a| dep.contains(a))) { dep.insert(Atom::Phi(id)); changed = true; @@ -774,9 +730,7 @@ impl Ctx<'_> { for user in self.users.get(&v).into_iter().flatten() { let outside = match *user { User::Inst(b2, _) => !lp[b2], - User::Phi(b2, k2) => { - !lp[b2] && self.live.contains(&p.blocks[b2].phis[k2].value) - } + User::Phi(b2, k2) => !lp[b2] && self.live.contains(&p.blocks[b2].phis[k2].value), }; if outside { return Err((head, STALE)); @@ -806,8 +760,7 @@ pub(super) fn find(p: &Program, st: &Structured, why: bool) -> OwnBits { }; let ctx = ctx.get_or_insert_with(|| Ctx::new(p, st)); // (values only the section itself reads are not results) - let inside = - |u: &User| matches!(*u, User::Inst(b2, i) if b2 == b && i > s && i < sec.end); + let inside = |u: &User| matches!(*u, User::Inst(b2, i) if b2 == b && i > s && i < sec.end); if ctx.users.get(&t).is_none_or(|us| us.iter().all(inside)) { continue; } @@ -874,8 +827,8 @@ mod tests { w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13] w.extend_from_slice(latch); w.extend_from_slice(&[ - 0x8909_080B, // s_xor_b32 s9, s11, s8 - 0xBF06_0B08, // s_cmp_eq_u32 s8, s11 + 0x8909_080B, // s_xor_b32 s9, s11, s8 + 0xBF06_0B08, // s_cmp_eq_u32 s8, s11 0xBF84_0000 | (0x1_0000 - head - 1) as u32, // s_cbranch_scc0 again ]); w.extend_from_slice(after); @@ -906,13 +859,7 @@ mod tests { assert!(names.contains(&n), "{n} in {names:?}"); } // a loop: its last branch goes back to the copy of the bits still to visit - assert!( - p.blocks.iter().enumerate().any(|(b, blk)| blk - .exit - .successors() - .iter() - .any(|&s| s < b)) - ); + assert!(p.blocks.iter().enumerate().any(|(b, blk)| blk.exit.successors().iter().any(|&s| s < b))); let own = found(&p); // the OR is the section's last lane read, and the bits still to visit (v3) are alike let total = insts() @@ -950,12 +897,7 @@ mod tests { // s_add_i32 s14, s14, 1 where every lane passes, read after the loop // (v_mov_b32 v6, s14): one round for each bit any lane has let p = light_loop(true, &[ADD_BIT_NUMBER], &[0x810E_810E], &[0x7E0C_020E]); - assert!( - p.blocks - .iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "s_add_i32") - ); + assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_add_i32")); assert!(found(&p).totals.is_empty()); // (reading s14 there without counting in it is nothing of the loop's) let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020E]); @@ -966,12 +908,7 @@ mod tests { fn an_effect_where_every_lane_passes_is_not_the_lanes_own() { // ds_write_b32 v5, v5 after the body: once for each bit any lane has let p = light_loop(true, &[ADD_BIT_NUMBER], &[0xD834_0000, 0x0000_0505], &[]); - assert!( - p.blocks - .iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "ds_write_b32") - ); + assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "ds_write_b32")); assert!(found(&p).totals.is_empty()); } } diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs index d2a236f..9ec80fd 100644 --- a/crates/victory-shader/src/emit/rect.rs +++ b/crates/victory-shader/src/emit/rect.rs @@ -8,8 +8,8 @@ //! arguments stay the title's, and each rectangle arrives here as one //! triangle. //! -//! Which vertex is the corner between the other two varies: Grand Theft -//! Auto VI's full-screen rectangles come as top left, bottom left, bottom +//! Which vertex is the corner between the other two varies: +//! the title's full-screen rectangles come as top left, bottom left, bottom //! right (the second), its tiled lighting as top left, bottom left, top //! right (the first). The corner is the vertex that shares x with one of //! the others and y with the other; the fourth vertex lies opposite it, @@ -74,9 +74,7 @@ fn build(mut outputs: Vec, ps_inputs: &[SigElement]) -> Result V { } else { ("loadInput.i32", s.t.i32) }; - let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(col), s.m.i32(vertex)]; + let args = [ + s.m.i32(id as u32), + s.m.i32(0), + s.m.i8(col), + s.m.i32(vertex), + ]; let entry = s.entry; s.op(entry, name, Attr::ReadNone, ty, 4, &args) } @@ -412,9 +415,6 @@ mod tests { root_srvs: Vec::new(), root_uavs: Vec::new(), root_indexed_views: Vec::new(), - mesh_emu: None, - address_map: false, - descriptor_words: false, }; ( host(crate::native::HwStage::Vs, vs), @@ -478,10 +478,7 @@ mod tests { } let half = draw(None); let missing = half.iter().zip(&whole).filter(|(a, b)| a != b).count(); - assert!( - missing >= 24, - "{name}: only {missing} texels need the stage" - ); + assert!(missing >= 24, "{name}: only {missing} texels need the stage"); } } } diff --git a/crates/victory-shader/src/emit/root_view_tests.rs b/crates/victory-shader/src/emit/root_view_tests.rs deleted file mode 100644 index ceb4c30..0000000 --- a/crates/victory-shader/src/emit/root_view_tests.rs +++ /dev/null @@ -1,194 +0,0 @@ -//! End-to-end tests of scalar loads (`s_load_dword*`) from a root view's -//! address: synthetic GFX10 programs lowered to DXIL, validated by -//! `dxil.dll` when present, and run on the hardware GPU and on WARP. - -use super::host::{Dispatch, Host, Root, View}; -use super::{HostShader, lower, validator}; -use crate::native::{ - ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, -}; -use crate::{io, ir, resource, structure}; - -const S_ENDPGM: u32 = 0xBF81_0000; - -/// A root view in user SGPRs 0-1 (root parameter 0) and a table in user -/// SGPR 2 (root parameter 1) whose entry 0 is a raw UAV: dwords 2 and 3 -/// of the view's memory go to dwords 0 and 1 of the UAV. -const READ_DWORDS_2_AND_3: &[u32] = &[ - 0xF404_0100, - 0xFA00_0008, // s_load_dwordx2 s[4:5], s[0:1], 0x8 - 0xBE86_0302, // s_mov_b32 s6, s2 - 0xBE87_0380, // s_mov_b32 s7, 0 - 0xF408_0203, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], null - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0x7E02_0204, // v_mov_b32 v1, s4 - 0x7E04_0205, // v_mov_b32 v2, s5 - 0xE070_0000, - 0x8002_0100, // buffer_store_dword v1, off, s[8:11], 0 - 0xE070_0004, - 0x8002_0200, // buffer_store_dword v2, off, s[8:11], 0 offset:4 - S_ENDPGM, -]; - -/// [`READ_DWORDS_2_AND_3`] lowered with the root view of `kind`. -fn build(kind: ResourceType) -> HostShader { - let param = |root, sgprs, user_data, slot| RootParam { - root, - table_offset_dwords: 0, - sgprs, - base_register: 0, - user_data, - slot, - }; - let used = |kind, root, user_data, slot| UsedResource { - kind, - root, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data, - slot, - }; - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 8, - layout: vec![ - param(RootType::Descriptor, 2, 0, 0), - param(RootType::Table, 1, 2, 1), - ], - used: vec![ - used(kind, RootType::Descriptor, 0, 0), - used(ResourceType::Uav, RootType::Table, 2, 1), - ], - io: StageIo::Cs(ComputeIo { - rsrc2: 3 << 1, - threads: [1, 1, 1], - }), - code: READ_DWORDS_2_AND_3 - .iter() - .flat_map(|w| w.to_le_bytes()) - .collect(), - }; - let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - let names: Vec<_> = p - .blocks - .iter() - .flat_map(|b| b.insts.iter().map(|i| i.name())) - .collect(); - assert_eq!( - names, - [ - "s_load_dwordx2", - "s_mov_b32", - "s_mov_b32", - "s_load_dwordx4", - "v_mov_b32", - "v_mov_b32", - "buffer_store_dword", - "buffer_store_dword", - "s_endpgm", - ] - ); - 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"); - let lowered = 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, - crumbs: None, - emulate_mesh: false, - }) - .expect("lower"); - let shader = HostShader { - stage: HwStage::Cs, - dxil: lowered.dxil, - user_data: lowered.user_data, - samplers: lowered.samplers, - static_samplers: Vec::new(), - root_cbvs: lowered.root_cbvs, - root_srvs: lowered.root_srvs, - address_map: lowered.address_map, - descriptor_words: lowered.descriptor_words, - root_uavs: lowered.root_uavs, - root_indexed_views: Vec::new(), - mesh_emu: None, - }; - if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { - v.validate(&mut shader.dxil.clone()) - .expect("DXIL validation failed"); - } else { - eprintln!("no dxil.dll; validation skipped"); - } - shader -} - -#[test] -fn scalar_loads_read_a_root_srv_and_a_root_cbv() { - let _one = super::valu_tests::ONE_AT_A_TIME - .lock() - .unwrap_or_else(|e| e.into_inner()); - let data: Vec = (0..64).map(|i| 0x2000 + i).collect(); - for (kind, srv) in [(ResourceType::Srv, true), (ResourceType::Cbv, false)] { - let shader = build(kind); - assert_eq!( - (shader.root_srvs.len(), shader.root_cbvs.len()), - if srv { (1, 0) } else { (0, 1) }, - "{kind:?}: the root view the shader declares" - ); - for warp in [false, true] { - let host = match Host::new(warp) { - Ok(h) => h, - Err(e) if warp => { - eprintln!("no SM 6.6 WARP device ({e}); skipped"); - continue; - } - Err(e) => { - eprintln!("no SM 6.6 hardware device ({e}); skipped"); - continue; - } - }; - let label = if warp { "WARP" } else { "hardware" }; - let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; - for u in &shader.user_data { - assert_eq!(u.root, RootType::Table, "{u:?}"); - ud[u.index as usize] = 0; - } - let (root, pso) = host - .compute_pipeline(&shader) - .unwrap_or_else(|e| panic!("{label} {kind:?}: {e}")); - let out = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![ - (0, Root::Constants(ud)), - ( - 1, - Root::View { - srv, - data: data.clone(), - }, - ), - ], - views: &[View::RawUav(2)], - samplers: &[], - groups: [1, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{label} {kind:?}: {e}")); - assert_eq!(out[0], [0x2002, 0x2003], "{label} {kind:?}"); - eprintln!("{label}: scalar loads from a root {kind:?} exact"); - } - } -} diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 00875ed..dbce3db 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -1,7 +1,6 @@ //! A DXIL vertex, pixel, compute or mesh shader under construction: the module, //! the `dx.op` declarations it calls, its signatures and bound resources, -//! and the metadata and container that wrap it up (SM 6.6; validator 1.6, -//! or 1.8 for compute derivatives). +//! and the metadata and container that wrap it up (SM 6.6, validator 1.6). use super::bitcode::{Attr, Md, Module, Ty, V}; use super::container::{self, Binding, Psv, SigElement}; @@ -13,19 +12,6 @@ pub const SAMPLER_SPACE: u32 = 0; /// Where root CBVs and SRVs are bound: `b` and /// `t` in this space. pub const ROOT_CBV_SPACE: u32 = 1; -/// Where the address map is bound: `t0` in this space (a root SRV), when -/// the shader reads title memory at addresses it computes -/// ([`crate::resource::GLOBAL`]; see [`super::HostShader::address_map`]). -pub const ADDRESS_MAP_SPACE: u32 = 2; -/// Where the descriptor words are bound: `t0` in this space (a root SRV), -/// when the shader reads descriptors as numbers beyond what host views -/// tell (see [`super::HostShader::descriptor_words`]). -pub const DESCRIPTOR_WORDS_SPACE: u32 = 3; -/// Where mesh shader emulation binds its scratch UAV (`u0`), indirect slot -/// map / unpack vertex input SRV (`t0`), and group-base CBV (`b0`). Space 2 -/// and 3 are the fork's address map and descriptor words, so emulation uses -/// the next space rather than upstream's `MESH_EMU_SPACE = 2`. -pub const MESH_EMU_SPACE: u32 = 4; /// The root SRV `t` in [`ROOT_CBV_SPACE`] of a shader that /// reads buffers through descriptors it picks from the view heap at an @@ -87,15 +73,16 @@ pub const USER_VIEW_BIAS: u32 = 0x103; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { pub const RAW_BUFFERS: u64 = 1 << 4; + pub const DOUBLES: u64 = 1 << 2; pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; pub const WAVE_OPS: u64 = 1 << 19; pub const BARYCENTRICS: u64 = 1 << 22; pub const INT64: u64 = 1 << 20; - pub const ATOMIC_INT64_ON_TYPED_RESOURCE: u64 = 1 << 27; + pub const ATOMIC_TYPED64: u64 = 1 << 27; + pub const ATOMIC_HEAP64: u64 = 1 << 32; pub const RESOURCE_HEAP: u64 = 1 << 30; pub const SAMPLER_HEAP: u64 = 1 << 31; - pub const ATOMIC_INT64_ON_HEAP_RESOURCE: u64 = 1 << 32; } pub(crate) struct Types { @@ -157,33 +144,23 @@ pub(crate) struct Shader { pub geometry: Option, /// Dwords of user data the shader reads (0: no user-data buffer). pub user_data: u32, - /// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`]: `true` when - /// the sampler is a comparison sampler. - pub samplers: Vec, + /// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`]. + pub samplers: u32, + /// Bit n: immediate sampler n is a comparison sampler. + pub cmp_samplers: u64, /// Root CBVs read, by root parameter index, with their handles. pub root_cbvs: Vec<(u8, V)>, /// Root SRVs (raw buffers) read, likewise. pub root_srvs: Vec<(u8, V)>, - /// The address map's handle, once made ([`Shader::address_map_handle`]). - pub address_map: Option, - /// The descriptor words' handle, once made. - pub descriptor_words: Option, /// Root UAVs (raw buffers) read or written, likewise. pub root_uavs: Vec<(u8, V)>, - emu_cbv: Option, - emu_srv: Option, - emu_uav: Option, pub flags: u64, /// Heap handles made with a non-uniform index. pub nonuniform_handles: u32, - /// Heap handles annotated as constant buffers. - pub cbuffer_handles: u32, /// A compute shader with this thread-group size. pub threads: Option<[u32; 3]>, /// The wave size a compute shader requires (`WaveSize`). pub wave_size: Option, - /// Compute derivatives require validator 1.8 rather than 1.6 or 1.7. - compute_derivatives: bool, /// Thread-group shared memory, in dwords. pub lds_dwords: u32, lds: Option, @@ -229,21 +206,15 @@ impl Shader { mesh: None, geometry: None, user_data: 0, - samplers: Vec::new(), + samplers: 0, + cmp_samplers: 0, root_cbvs: Vec::new(), root_srvs: Vec::new(), - address_map: None, - descriptor_words: None, root_uavs: Vec::new(), - emu_cbv: None, - emu_srv: None, - emu_uav: None, flags: 0, nonuniform_handles: 0, - cbuffer_handles: 0, threads: None, wave_size: None, - compute_derivatives: false, lds_dwords: 0, lds: None, main, @@ -273,19 +244,6 @@ impl Shader { opcode: u32, args: &[V], ) -> V { - // Validators before 1.8 reject gradient operations outside the - // pixel stage. This set matches DXC's gradient classification: - // the implicit-derivative samples (60/61/64) and the LOD query - // (81), plus the explicit derivatives (83..=86). Bfi and the dot - // products (53..=56) are arithmetic and stay on 1.6, and - // SampleGrad/SampleLevel (62/63) take explicit gradients, so the - // validator already accepts them in compute. - if self.threads.is_some() - && self.mesh.is_none() - && matches!(opcode, 60 | 61 | 64 | 81 | 83..=86) - { - self.compute_derivatives = true; - } let mut params = vec![self.t.i32]; params.extend(args.iter().map(|&a| self.m.type_of(a))); let fty = self.m.func_ty(ret, params); @@ -369,106 +327,6 @@ impl Shader { h } - /// The handle of the mesh emulation group-base CBV (`b0` in - /// [`MESH_EMU_SPACE`]). - pub fn emu_cbv_handle(&mut self) -> V { - if let Some(h) = self.emu_cbv { - return h; - } - let z = self.m.i32(0); - let bind = [z, z, self.m.i32(MESH_EMU_SPACE), self.m.i8(2)]; - let bind = self.m.aggregate(self.t.bind, &bind); - let f = self.m.bool(false); - let block = self.entry; - let h = self.op( - block, - "createHandleFromBinding", - Attr::ReadNone, - self.t.handle, - 217, - &[bind, z, f], - ); - let h = self.annotate(block, h, 13, 16); - self.emu_cbv = Some(h); - h - } - - /// The handle of the mesh emulation raw SRV (`t0` in [`MESH_EMU_SPACE`]). - pub fn emu_srv_handle(&mut self) -> V { - if let Some(h) = self.emu_srv { - return h; - } - let h = self.space_handle(MESH_EMU_SPACE); - self.emu_srv = Some(h); - h - } - - /// The handle of the mesh emulation raw UAV (`u0` in [`MESH_EMU_SPACE`]). - pub fn emu_uav_handle(&mut self) -> V { - if let Some(h) = self.emu_uav { - return h; - } - let z = self.m.i32(0); - let bind = [z, z, self.m.i32(MESH_EMU_SPACE), self.m.i8(1)]; - let bind = self.m.aggregate(self.t.bind, &bind); - let f = self.m.bool(false); - let block = self.entry; - let h = self.op( - block, - "createHandleFromBinding", - Attr::ReadNone, - self.t.handle, - 217, - &[bind, z, f], - ); - let h = self.annotate(block, h, 11 | 0x1000, 0); - self.flags |= flags::RAW_BUFFERS; - self.emu_uav = Some(h); - h - } - - /// The handle of the address map (`t0` in [`ADDRESS_MAP_SPACE`], a raw - /// buffer), made in the entry block. - pub fn address_map_handle(&mut self) -> V { - if let Some(h) = self.address_map { - return h; - } - let h = self.space_handle(ADDRESS_MAP_SPACE); - self.address_map = Some(h); - h - } - - /// The handle of the descriptor words (`t0` in - /// [`DESCRIPTOR_WORDS_SPACE`], a raw buffer), made in the entry block. - pub fn descriptor_words_handle(&mut self) -> V { - if let Some(h) = self.descriptor_words { - return h; - } - let h = self.space_handle(DESCRIPTOR_WORDS_SPACE); - self.descriptor_words = Some(h); - h - } - - /// A raw buffer bound at `t0` in `space`, made in the entry block. - fn space_handle(&mut self, space: u32) -> V { - let r = self.m.i32(0); - let bind = [r, r, self.m.i32(space), self.m.i8(0)]; - let bind = self.m.aggregate(self.t.bind, &bind); - let f = self.m.bool(false); - let block = self.entry; - let h = self.op( - block, - "createHandleFromBinding", - Attr::ReadNone, - self.t.handle, - 217, - &[bind, r, f], - ); - let h = self.annotate(block, h, 11, 0); - self.flags |= flags::RAW_BUFFERS; - h - } - /// The handle of the root UAV (a raw buffer) of root parameter `slot`: /// `u` in [`ROOT_CBV_SPACE`]. pub fn root_uav_handle(&mut self, slot: u8) -> V { @@ -494,9 +352,9 @@ impl Shader { h } - /// The handle of immediate sampler `n` (a comparison sampler when - /// `comparison` is set). - pub fn sampler_handle(&mut self, block: usize, n: u32, comparison: bool) -> V { + /// The handle of immediate sampler `n` (a comparison sampler when its + /// bit in `cmp_samplers` is set). + pub fn sampler_handle(&mut self, block: usize, n: u32) -> V { let bind = [ self.m.i32(n), self.m.i32(n), @@ -513,7 +371,11 @@ impl Shader { 217, &[bind, i, f], ); - let cmp = if comparison { 0x8000 } else { 0 }; + let cmp = if self.cmp_samplers >> n & 1 != 0 { + 0x8000 + } else { + 0 + }; self.annotate(block, h, 14 | cmp, 0) } @@ -546,14 +408,9 @@ impl Shader { let index = if !sampler && limit != 0 { let null = self.m.i32(limit); let i32t = self.t.i32; - self.op( - block, - "binary.i32", - Attr::ReadNone, - i32t, - 40, - &[index, null], - ) + let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null]); + self.m.tag(v, super::bitcode::Tag::Clamp); + v } else if sampler { // A sampler heap has at most 2,048 samplers on any host: an // index past that (a number read from memory the host has not @@ -562,14 +419,9 @@ impl Shader { // heap smaller than 2,048 would need. let last = self.m.i32(2047); let i32t = self.t.i32; - self.op( - block, - "binary.i32", - Attr::ReadNone, - i32t, - 40, - &[index, last], - ) + let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]); + self.m.tag(v, super::bitcode::Tag::Clamp); + v } else { index }; @@ -579,7 +431,6 @@ impl Shader { flags::RESOURCE_HEAP }; self.nonuniform_handles += u32::from(nonuniform); - self.cbuffer_handles += u32::from(props.0 == 13); let (s, n) = (self.m.bool(sampler), self.m.bool(nonuniform)); let h = self.op( block, @@ -596,6 +447,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 clean-up, before anything is declared about the code: a + // feature whose last use it removed must not be declared (the + // validator compares the flags with what the code uses). + let passes = super::shader_opt() & super::bitcode::opt::MODULE; + if passes != 0 { + self.m.optimise(passes); + let used = self.m.usage(); + for (flag, used) in [ + (flags::WAVE_OPS, used.wave_ops), + (flags::INT64, used.int64), + (flags::TYPED_UAV_LOADS, used.typed_uav_loads), + (flags::RESOURCE_HEAP, used.heap_views), + (flags::SAMPLER_HEAP, used.heap_samplers), + (flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64, used.atomic64), + ] { + if !used { + self.flags &= !flag; + } + } + } let mut resources = None; let mut bindings = Vec::new(); let i32c = |s: &mut Self, v: u32| { @@ -603,15 +474,10 @@ impl Shader { s.m.md_value(c) }; if self.user_data > 0 - || !self.samplers.is_empty() + || self.samplers > 0 || !self.root_cbvs.is_empty() || !self.root_srvs.is_empty() - || self.address_map.is_some() - || self.descriptor_words.is_some() || !self.root_uavs.is_empty() - || self.emu_cbv.is_some() - || self.emu_srv.is_some() - || self.emu_uav.is_some() { let empty = self.m.md_str(""); let mut cbvs = None; @@ -662,62 +528,24 @@ impl Shader { dxil_kind: 13, }); } - if self.emu_cbv.is_some() { - let arr = self.m.array(4, self.t.i32); - let ty = self.m.named_struct("EmuConst", vec![arr]); - let p = self.m.ptr(ty); - let u = self.m.undef(p); - let ops = vec![ - Some(i32c(&mut self, cbv_list.len() as u32)), - Some(self.m.md_value(u)), - Some(empty), - Some(i32c(&mut self, MESH_EMU_SPACE)), - Some(i32c(&mut self, 0)), - Some(i32c(&mut self, 1)), - Some(i32c(&mut self, 16)), - None, - ]; - cbv_list.push(Some(self.m.md_node(ops))); - bindings.push(Binding { - kind: 2, - space: MESH_EMU_SPACE, - register: 0, - dxil_kind: 13, - }); - } if !cbv_list.is_empty() { cbvs = Some(self.m.md_node(cbv_list)); } let mut srvs = None; - // Raw buffers: root SRVs, then the address map. - let mut raw: Vec<(u32, u32)> = self - .root_srvs - .iter() - .map(|&(slot, _)| (ROOT_CBV_SPACE, u32::from(slot))) - .collect(); - if self.address_map.is_some() { - raw.push((ADDRESS_MAP_SPACE, 0)); - } - if self.descriptor_words.is_some() { - raw.push((DESCRIPTOR_WORDS_SPACE, 0)); - } - if self.emu_srv.is_some() { - raw.push((MESH_EMU_SPACE, 0)); - } - if !raw.is_empty() { + if !self.root_srvs.is_empty() { let ty = self .m .named_struct("struct.ByteAddressBuffer", vec![self.t.i32]); let p = self.m.ptr(ty); let u = self.m.undef(p); let mut list = Vec::new(); - for (n, (space, register)) in raw.into_iter().enumerate() { + for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() { let ops = vec![ Some(i32c(&mut self, n as u32)), Some(self.m.md_value(u)), Some(empty), - Some(i32c(&mut self, space)), - Some(i32c(&mut self, register)), + Some(i32c(&mut self, ROOT_CBV_SPACE)), + Some(i32c(&mut self, u32::from(slot))), Some(i32c(&mut self, 1)), Some(i32c(&mut self, 11)), Some(i32c(&mut self, 0)), @@ -726,23 +554,15 @@ impl Shader { list.push(Some(self.m.md_node(ops))); bindings.push(Binding { kind: 4, - space, - register, + space: ROOT_CBV_SPACE, + register: u32::from(slot), dxil_kind: 11, }); } srvs = Some(self.m.md_node(list)); } let mut uavs = None; - let mut raw_uavs: Vec<(u32, u32)> = self - .root_uavs - .iter() - .map(|&(slot, _)| (ROOT_CBV_SPACE, u32::from(slot))) - .collect(); - if self.emu_uav.is_some() { - raw_uavs.push((MESH_EMU_SPACE, 0)); - } - if !raw_uavs.is_empty() { + if !self.root_uavs.is_empty() { let ty = self .m .named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]); @@ -751,7 +571,7 @@ impl Shader { let no = self.m.bool(false); let no = self.m.md_value(no); let mut list = Vec::new(); - for (n, (space, register)) in raw_uavs.into_iter().enumerate() { + for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() { // Id, variable, name, space, lower bound, range size, // shape (11: raw buffer), globally coherent, counter, // rasterizer ordered, no extra properties. @@ -759,8 +579,8 @@ impl Shader { Some(i32c(&mut self, n as u32)), Some(self.m.md_value(u)), Some(empty), - Some(i32c(&mut self, space)), - Some(i32c(&mut self, register)), + Some(i32c(&mut self, ROOT_CBV_SPACE)), + Some(i32c(&mut self, u32::from(slot))), Some(i32c(&mut self, 1)), Some(i32c(&mut self, 11)), Some(no), @@ -771,22 +591,21 @@ impl Shader { list.push(Some(self.m.md_node(ops))); bindings.push(Binding { kind: 7, - space, - register, + space: ROOT_CBV_SPACE, + register: u32::from(slot), dxil_kind: 11, }); } uavs = Some(self.m.md_node(list)); } let mut samplers = None; - if !self.samplers.is_empty() { + if self.samplers > 0 { let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]); let p = self.m.ptr(ty); let u = self.m.undef(p); let mut list = Vec::new(); - for n in 0..self.samplers.len() { - let kind = u32::from(self.samplers[n]); - let n = n as u32; + for n in 0..self.samplers { + let kind = (self.cmp_samplers >> n & 1) as u32; let ops = vec![ Some(i32c(&mut self, n)), Some(self.m.md_value(u)), @@ -933,10 +752,7 @@ impl Shader { let six = i32c(&mut self, 6); let version = self.m.md_node(vec![Some(one), Some(six)]); self.m.named_md("dx.version", vec![version]); - let val_minor = if self.compute_derivatives { 8 } else { 6 }; - let val_minor = i32c(&mut self, val_minor); - let val_version = self.m.md_node(vec![Some(one), Some(val_minor)]); - self.m.named_md("dx.valver", vec![val_version]); + self.m.named_md("dx.valver", vec![version]); // Program kinds: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh. let (name, kind) = match (self.threads, self.pixel) { _ if self.mesh.is_some() => ("ms", 13u32), @@ -951,6 +767,7 @@ impl Shader { self.m.named_md("dx.entryPoints", vec![entry]); let bitcode = self.m.write(); + super::bitcode::census::note(&self.m, &bitcode); let mut dxil = Vec::with_capacity(24 + bitcode.len()); dxil.extend((kind << 16 | 0x66).to_le_bytes()); dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes()); @@ -961,6 +778,9 @@ impl Shader { dxil.extend(&bitcode); let mut features = 0u64; + if self.flags & flags::DOUBLES != 0 { + features |= 0x1; + } if self.flags & flags::STENCIL_REF != 0 { features |= 0x200; } @@ -973,9 +793,6 @@ impl Shader { if self.flags & flags::INT64 != 0 { features |= 0x8000; } - if self.flags & flags::ATOMIC_INT64_ON_TYPED_RESOURCE != 0 { - features |= 0x40_0000; - } if self.flags & flags::BARYCENTRICS != 0 { features |= 0x2_0000; } @@ -985,7 +802,10 @@ impl Shader { if self.flags & flags::SAMPLER_HEAP != 0 { features |= 0x400_0000; } - if self.flags & flags::ATOMIC_INT64_ON_HEAP_RESOURCE != 0 { + if self.flags & flags::ATOMIC_TYPED64 != 0 { + features |= 0x40_0000; + } + if self.flags & flags::ATOMIC_HEAP64 != 0 { features |= 0x1000_0000; } let sfi0 = features.to_le_bytes(); @@ -1007,7 +827,6 @@ impl Shader { bindings: &bindings, threads: self.threads.unwrap_or_default(), wave_size: self.wave_size, - validator18: self.compute_derivatives, }); let hash = [0u8; 20]; let psg1 = container::signature(&self.prims, false); @@ -1069,209 +888,3 @@ impl Shader { Some(self.m.md_node(list)) } } - -#[cfg(all(test, windows))] -mod tests { - use super::super::HostShader; - use super::super::bitcode::{Bin, Term, pred}; - use super::super::host::Host; - use super::super::validator; - use super::*; - use crate::native::HwStage; - - fn validate_and_create_cs_pso(mut dxil: Vec) { - let path = validator::Validator::default_path(); - if let Ok(mut validator) = validator::Validator::load(path.as_deref()) { - validator.validate(&mut dxil).unwrap(); - } - let hs = HostShader { - stage: HwStage::Cs, - dxil, - user_data: Vec::new(), - samplers: Vec::new(), - static_samplers: Vec::new(), - root_cbvs: Vec::new(), - root_srvs: Vec::new(), - address_map: false, - descriptor_words: false, - root_uavs: Vec::new(), - root_indexed_views: Vec::new(), - mesh_emu: None, - }; - if let Ok(host) = Host::new(false) { - host.compute_pipeline(&hs).unwrap(); - } - if let Ok(warp) = Host::new(true) { - warp.compute_pipeline(&hs).unwrap(); - } - } - - #[test] - fn two_empty_latches_to_same_header_validate() { - let mut s = Shader::new(false); - s.threads = Some([1, 1, 1]); - let entry = s.entry; - let head = s.m.new_block(); - let body = s.m.new_block(); - let latch_a = s.m.new_block(); - let latch_b = s.m.new_block(); - let exit = s.m.new_block(); - - let i32t = s.t.i32; - let zero = s.m.i32(0); - let one = s.m.i32(1); - let two = s.m.i32(2); - let ten = s.m.i32(10); - s.m.terminate(entry, Term::Br(head)); - - let acc = s.m.phi(head, i32t); - let go = s.m.cmp(head, pred::IULT, acc, ten); - s.m.terminate(head, Term::CondBr(go, body, exit)); - - let bit = s.m.bin(body, Bin::And, acc, one); - let pick = s.m.cmp(body, pred::EQ, bit, zero); - s.m.terminate(body, Term::CondBr(pick, latch_a, latch_b)); - - // Two distinct empty back-edge latches from `body` to `head` carry - // distinct incoming values; only one may fold into `body`. - s.m.terminate(latch_a, Term::Br(head)); - s.m.terminate(latch_b, Term::Br(head)); - let next_a = s.m.bin(body, Bin::Add, acc, one); - let next_b = s.m.bin(body, Bin::Add, acc, two); - s.m.set_phi( - acc, - vec![(zero, entry), (next_a, latch_a), (next_b, latch_b)], - ); - - s.m.terminate(exit, Term::Ret); - validate_and_create_cs_pso(s.finish()); - } - - #[test] - fn phi_with_unreachable_predecessor_validates() { - let mut s = Shader::new(false); - s.threads = Some([1, 1, 1]); - let entry = s.entry; - let dead = s.m.new_block(); - let join = s.m.new_block(); - - let i32t = s.t.i32; - let one = s.m.i32(1); - let live_val = s.m.bin(entry, Bin::Add, one, one); - s.m.terminate(entry, Term::Br(join)); - - let dead_val = s.m.bin(dead, Bin::Add, one, one); - s.m.terminate(dead, Term::Br(join)); - - let merged = s.m.phi(join, i32t); - s.m.set_phi(merged, vec![(live_val, entry), (dead_val, dead)]); - let _used = s.m.bin(join, Bin::Add, merged, one); - s.m.terminate(join, Term::Ret); - validate_and_create_cs_pso(s.finish()); - } - - /// Builds a compute shader calling `opcode` and returns its container - /// plus the derivative flag as detected by `op`. `Some(v)` overrides - /// the flag before the container is written. - fn compute_with_op( - opcode: u32, - name: &str, - attr: Attr, - args: usize, - validator18: Option, - ) -> (Vec, bool) { - let mut s = Shader::new(false); - s.threads = Some([32, 1, 1]); - s.wave_size = Some(32); - let block = s.entry; - let zero = s.m.f32(0); - let args = vec![zero; args]; - let ret = s.t.f32; - s.op(block, name, attr, ret, opcode, &args); - let detected = s.compute_derivatives; - if let Some(v) = validator18 { - s.compute_derivatives = v; - } - s.m.terminate(block, Term::Ret); - (s.finish(), detected) - } - - #[test] - fn compute_implicit_sample_validates() { - let mut s = Shader::new(false); - s.threads = Some([32, 1, 1]); - s.wave_size = Some(32); - s.samplers = vec![false]; - let block = s.entry; - let index = s.m.i32(0); - let texture = s.heap_handle(block, index, false, false, (2, 1033)); - let sampler = s.sampler_handle(block, 0, false); - let zero = s.m.f32(0); - let fu = s.m.undef(s.t.f32); - let iu = s.m.undef(s.t.i32); - let args = [texture, sampler, zero, zero, fu, fu, iu, iu, iu, fu]; - let ret = s.t.res_ret; - s.op(block, "sample.f32", Attr::ReadOnly, ret, 60, &args); - assert!(s.compute_derivatives); - s.m.terminate(block, Term::Ret); - let mut dxil = s.finish(); - let path = validator::Validator::default_path(); - let Ok(mut validator) = validator::Validator::load(path.as_deref()) else { - eprintln!("no dxil.dll; skipped"); - return; - }; - validator.validate(&mut dxil).unwrap(); - - // The same module declared as validator 1.6 must be rejected. - let mut legacy = { - let mut s = Shader::new(false); - s.threads = Some([32, 1, 1]); - s.wave_size = Some(32); - s.samplers = vec![false]; - let block = s.entry; - let index = s.m.i32(0); - let texture = s.heap_handle(block, index, false, false, (2, 1033)); - let sampler = s.sampler_handle(block, 0, false); - let zero = s.m.f32(0); - let fu = s.m.undef(s.t.f32); - let iu = s.m.undef(s.t.i32); - let args = [texture, sampler, zero, zero, fu, fu, iu, iu, iu, fu]; - let ret = s.t.res_ret; - s.op(block, "sample.f32", Attr::ReadOnly, ret, 60, &args); - s.compute_derivatives = false; - s.m.terminate(block, Term::Ret); - s.finish() - }; - assert!(validator.validate(&mut legacy).is_err()); - } - - #[test] - fn compute_explicit_derivative_validates() { - // DerivCoarseX (83): rejected before validator 1.8 like the - // implicit-derivative samples. - let (mut dxil, detected) = compute_with_op(83, "unary.f32", Attr::ReadNone, 1, Some(true)); - assert!(detected); - let (mut legacy, _) = compute_with_op(83, "unary.f32", Attr::ReadNone, 1, Some(false)); - let path = validator::Validator::default_path(); - let Ok(mut validator) = validator::Validator::load(path.as_deref()) else { - eprintln!("no dxil.dll; skipped"); - return; - }; - validator.validate(&mut dxil).unwrap(); - assert!(validator.validate(&mut legacy).is_err()); - } - - #[test] - fn compute_dot3_stays_on_validator_1_6() { - // Dot3 (55) is arithmetic, not a gradient op: it must not bump the - // validator version, and the resulting 1.6 module validates. - let (mut dxil, detected) = compute_with_op(55, "dot3.f32", Attr::ReadNone, 6, None); - assert!(!detected); - let path = validator::Validator::default_path(); - let Ok(mut validator) = validator::Validator::load(path.as_deref()) else { - eprintln!("no dxil.dll; skipped"); - return; - }; - validator.validate(&mut dxil).unwrap(); - } -} diff --git a/crates/victory-shader/src/emit/validator.rs b/crates/victory-shader/src/emit/validator.rs index 5951f8a..32171c7 100644 --- a/crates/victory-shader/src/emit/validator.rs +++ b/crates/victory-shader/src/emit/validator.rs @@ -5,11 +5,9 @@ //! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's //! `bin\\x64\dxil.dll`, else wherever `LoadLibrary` finds it. -use std::ffi::{OsStr, c_void}; -use std::os::windows::ffi::OsStrExt; +use std::ffi::c_void; use std::path::PathBuf; -use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE}; use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; type Hresult = i32; @@ -34,7 +32,6 @@ const IN_PLACE_EDIT: u32 = 1; type CreateInstance = unsafe extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> Hresult; -type FreeModule = unsafe extern "system" fn(HMODULE) -> i32; /// COM object: a pointer to a table of method pointers. type Object = *mut *const usize; @@ -111,27 +108,12 @@ static BLOB_VTABLE: BlobVtable = BlobVtable { len: blob_len, }; -struct LoadedModule { - handle: HMODULE, - free: FreeModule, -} - -impl Drop for LoadedModule { - fn drop(&mut self) { - // SAFETY: construction transfers one reference to the module. - unsafe { (self.free)(self.handle) }; - } -} - pub struct Validator { object: Object, - // Field drops run after Validator::drop releases the COM interface. - _module: Option, } // SAFETY: the validator object is free-threaded (DXC's validator has no -// thread affinity); calls are serialised by `&mut self`. The module reference -// belongs to the process and can be released from another thread. +// thread affinity); calls are serialised by `&mut self`. unsafe impl Send for Validator {} impl Validator { @@ -153,55 +135,35 @@ impl Validator { /// Loads `path`'s validator (or `dxil.dll` from the DLL search path). pub fn load(path: Option<&std::path::Path>) -> Result { - let target: &OsStr = path.map_or(OsStr::new("dxil.dll"), |p| p.as_os_str()); - let name: Vec = target.encode_wide().chain([0]).collect(); + let name: Vec = path + .map_or_else(|| "dxil.dll".into(), |p| p.as_os_str().to_owned()) + .to_string_lossy() + .encode_utf16() + .chain([0]) + .collect(); // SAFETY: plain Win32 calls with a NUL-terminated name. unsafe { let module = LoadLibraryW(name.as_ptr()); if module.is_null() { - return Err(format!("cannot load {}", target.to_string_lossy())); + return Err(format!("cannot load {}", String::from_utf16_lossy(&name))); } - Self::from_module(module, FreeLibrary, |module| { - let create = GetProcAddress(module, c"DxcCreateInstance".as_ptr().cast()) - .ok_or("dxil.dll lacks DxcCreateInstance")?; - let create: CreateInstance = std::mem::transmute(create); - let mut object = std::ptr::null_mut(); - let hr = create(&CLSID_DXC_VALIDATOR, &IID_IDXC_VALIDATOR, &mut object); - if hr < 0 || object.is_null() { - return Err(format!("DxcCreateInstance(validator) failed: {hr:#x}")); - } - Ok(object.cast()) + let create = GetProcAddress(module, c"DxcCreateInstance".as_ptr().cast()) + .ok_or("dxil.dll lacks DxcCreateInstance")?; + let create: CreateInstance = std::mem::transmute(create); + let mut object = std::ptr::null_mut(); + let hr = create(&CLSID_DXC_VALIDATOR, &IID_IDXC_VALIDATOR, &mut object); + if hr < 0 || object.is_null() { + return Err(format!("DxcCreateInstance(validator) failed: {hr:#x}")); + } + Ok(Validator { + object: object.cast(), }) } } - // SAFETY: `module` is one owned reference accepted by `free`. On success, - // `create` returns one owned reference to a live validator interface. - unsafe fn from_module( - module: HMODULE, - free: FreeModule, - create: impl FnOnce(HMODULE) -> Result, - ) -> Result { - let module = LoadedModule { - handle: module, - free, - }; - Ok(Self { - object: create(module.handle)?, - _module: Some(module), - }) - } - /// Validates `container` and signs it in place; the error text if it /// is rejected. pub fn validate(&mut self, container: &mut [u8]) -> Result<(), String> { - // `dxil.dll` trusts header size/part fields on `"DXBC"` blobs before - // checking `IDxcBlob::GetBufferSize()`, causing an access violation on - // truncated/malformed containers. Pre-validate DXBC framing in safe Rust - // while leaving non-DXBC unit-test stubs untouched. - if container.starts_with(b"DXBC") { - crate::dxbc::Container::parse(container).map_err(|e| e.to_string())?; - } let mut blob = Blob { vtable: &BLOB_VTABLE, data: container.as_mut_ptr(), @@ -225,11 +187,7 @@ impl Validator { let mut status = 0; let get_status: unsafe extern "system" fn(Object, *mut Hresult) -> Hresult = method(result, 3); - let hr = get_status(result, &mut status); - if hr < 0 { - release(result); - return Err(format!("GetStatus failed: {hr:#x}")); - } + get_status(result, &mut status); let mut text = String::new(); if status < 0 { let mut errors: Object = std::ptr::null_mut(); @@ -238,17 +196,11 @@ impl Validator { if get_errors(result, &mut errors) >= 0 && !errors.is_null() { let ptr: unsafe extern "system" fn(Object) -> *const u8 = method(errors, 3); let len: unsafe extern "system" fn(Object) -> usize = method(errors, 4); - let len = len(errors); - if len != 0 { - let ptr = ptr(errors); - if !ptr.is_null() { - let bytes = std::slice::from_raw_parts(ptr, len); - text = String::from_utf8_lossy(bytes) - .trim_end_matches('\0') - .trim() - .into(); - } - } + let bytes = std::slice::from_raw_parts(ptr(errors), len(errors)); + text = String::from_utf8_lossy(bytes) + .trim_end_matches('\0') + .trim() + .into(); release(errors); } if text.is_empty() { @@ -267,389 +219,3 @@ impl Drop for Validator { unsafe { release(self.object) }; } } - -#[cfg(test)] -mod tests { - use super::*; - - const E_FAIL: Hresult = 0x8000_4005_u32 as Hresult; - const E_INVALIDARG: Hresult = 0x8007_0057_u32 as Hresult; - - #[derive(Default)] - struct Scenario { - validate_hr: Hresult, - omit_result: bool, - status_hr: Hresult, - status: Hresult, - errors_hr: Hresult, - diagnostic: Option<&'static [u8]>, - } - - #[repr(C)] - struct MockHeader { - vtable: *const usize, - releases: u32, - } - - #[repr(C)] - struct Mock { - header: MockHeader, - data: T, - } - - impl Mock { - fn new(vtable: &[usize], data: T) -> Self { - Self { - header: MockHeader { - vtable: vtable.as_ptr(), - releases: 0, - }, - data, - } - } - - fn object(&mut self) -> Object { - std::ptr::from_mut(self).cast() - } - } - - struct MockValidator { - hr: Hresult, - result: Object, - } - - struct MockResult { - status_hr: Hresult, - status: Hresult, - errors_hr: Hresult, - errors: Object, - error_queries: u32, - } - - struct MockErrors { - bytes: &'static [u8], - pointer_queries: u32, - } - - unsafe extern "system" fn mock_release(this: Object) -> u32 { - // SAFETY: every mock object starts with MockHeader. - unsafe { (*this.cast::()).releases += 1 }; - 0 - } - - unsafe extern "system" fn mock_validate( - this: Object, - blob: *mut Blob, - flags: u32, - out: *mut Object, - ) -> Hresult { - // SAFETY: validation invokes this slot on Mock with a - // live input blob and a writable result pointer. - unsafe { - let data = &(*this.cast::>()).data; - let vtable = &*(*blob).vtable; - if flags != IN_PLACE_EDIT || (vtable.len)(blob) != 3 { - return E_INVALIDARG; - } - *(vtable.ptr)(blob).add(1) = 0x5a; - *out = data.result; - data.hr - } - } - - unsafe extern "system" fn mock_status(this: Object, out: *mut Hresult) -> Hresult { - // SAFETY: this slot belongs to Mock and out is writable. - unsafe { - let data = &(*this.cast::>()).data; - if data.status_hr >= 0 { - *out = data.status; - } - data.status_hr - } - } - - unsafe extern "system" fn mock_errors(this: Object, out: *mut Object) -> Hresult { - // SAFETY: this slot belongs to Mock and out is writable. - unsafe { - let data = &mut (*this.cast::>()).data; - data.error_queries += 1; - if data.errors_hr >= 0 { - *out = data.errors; - } - data.errors_hr - } - } - - unsafe extern "system" fn mock_error_ptr(this: Object) -> *const u8 { - // SAFETY: this slot belongs to Mock. - unsafe { - let data = &mut (*this.cast::>()).data; - data.pointer_queries += 1; - if data.bytes.is_empty() { - std::ptr::null() - } else { - data.bytes.as_ptr() - } - } - } - - unsafe extern "system" fn mock_error_len(this: Object) -> usize { - // SAFETY: this slot belongs to Mock. - let data = unsafe { &(*this.cast::>()).data }; - data.bytes.len() - } - - fn validate_mock(scenario: Scenario) -> (Result<(), String>, [u8; 3], [u32; 4]) { - let release = mock_release as *const () as usize; - let validate_vtable = [0, 0, release, mock_validate as *const () as usize]; - let result_vtable = [ - 0, - 0, - release, - mock_status as *const () as usize, - 0, - mock_errors as *const () as usize, - ]; - let errors_vtable = [ - 0, - 0, - release, - mock_error_ptr as *const () as usize, - mock_error_len as *const () as usize, - ]; - let mut errors = Mock::new( - &errors_vtable, - MockErrors { - bytes: scenario.diagnostic.unwrap_or_default(), - pointer_queries: 0, - }, - ); - let mut result = Mock::new( - &result_vtable, - MockResult { - status_hr: scenario.status_hr, - status: scenario.status, - errors_hr: scenario.errors_hr, - errors: scenario - .diagnostic - .map_or(std::ptr::null_mut(), |_| errors.object()), - error_queries: 0, - }, - ); - let mut validator = Mock::new( - &validate_vtable, - MockValidator { - hr: scenario.validate_hr, - result: if scenario.omit_result || scenario.validate_hr < 0 { - std::ptr::null_mut() - } else { - result.object() - }, - }, - ); - let mut bytes = [0x11, 0x22, 0x33]; - let outcome = Validator { - object: validator.object(), - _module: None, - } - .validate(&mut bytes); - assert_eq!(validator.header.releases, 1); - let calls = [ - result.header.releases, - result.data.error_queries, - errors.header.releases, - errors.data.pointer_queries, - ]; - (outcome, bytes, calls) - } - - #[test] - fn failed_status_query_is_an_error_and_releases_the_result() { - let (outcome, _, calls) = validate_mock(Scenario { - status_hr: E_FAIL, - ..Scenario::default() - }); - assert_eq!(outcome, Err("GetStatus failed: 0x80004005".into())); - assert_eq!(calls, [1, 0, 0, 0]); - } - - #[test] - fn empty_diagnostic_needs_no_buffer_pointer() { - let (outcome, _, calls) = validate_mock(Scenario { - status: E_INVALIDARG, - diagnostic: Some(b""), - ..Scenario::default() - }); - assert_eq!(outcome, Err("rejected (0x80070057)".into())); - assert_eq!(calls, [1, 1, 1, 0]); - } - - #[test] - fn validation_passes_the_live_bytes_and_releases_the_result() { - let (outcome, bytes, calls) = validate_mock(Scenario { - validate_hr: 1, - status_hr: 1, - status: 1, - ..Scenario::default() - }); - assert_eq!(outcome, Ok(())); - assert_eq!(bytes, [0x11, 0x5a, 0x33]); - assert_eq!(calls, [1, 0, 0, 0]); - } - - #[test] - fn failed_validation_or_missing_result_is_an_error() { - for (validate_hr, expected) in [(E_FAIL, "0x80004005"), (0, "0x0")] { - let (outcome, _, calls) = validate_mock(Scenario { - validate_hr, - omit_result: true, - ..Scenario::default() - }); - assert_eq!(outcome, Err(format!("Validate failed: {expected}"))); - assert_eq!(calls, [0; 4]); - } - } - - #[test] - fn rejection_returns_trimmed_lossy_diagnostic_and_releases_both_objects() { - let (outcome, _, calls) = validate_mock(Scenario { - status: E_INVALIDARG, - diagnostic: Some(b" invalid \xff signature\r\n\0\0"), - ..Scenario::default() - }); - assert_eq!(outcome, Err("invalid \u{fffd} signature".into())); - assert_eq!(calls, [1, 1, 1, 1]); - } - - #[test] - fn rejection_falls_back_to_status_without_a_diagnostic() { - for (errors_hr, diagnostic, diagnostic_releases) in [ - (E_FAIL, Some(&b"unavailable"[..]), 0), - (0, None, 0), - (0, Some(&b" \r\n\0"[..]), 1), - ] { - let (outcome, _, calls) = validate_mock(Scenario { - status: E_INVALIDARG, - errors_hr, - diagnostic, - ..Scenario::default() - }); - assert_eq!(outcome, Err("rejected (0x80070057)".into())); - assert_eq!(calls, [1, 1, diagnostic_releases, diagnostic_releases]); - } - } - - #[test] - fn blob_exposes_only_iunknown_and_idxcblob() { - let mut bytes = [1, 2, 3]; - let mut blob = Blob { - vtable: &BLOB_VTABLE, - data: bytes.as_mut_ptr(), - len: bytes.len(), - }; - let this = std::ptr::from_mut(&mut blob); - // SAFETY: the vtable belongs to the live stack blob and each query - // uses an initialized IID and a writable output slot. - unsafe { - let mut out = std::ptr::null_mut(); - for iid in [IUNKNOWN, IDXC_BLOB] { - assert_eq!((BLOB_VTABLE.qi)(this, &iid, &mut out), 0); - assert_eq!(out, this.cast()); - } - assert_eq!( - (BLOB_VTABLE.qi)(this, &[0xff; 16], &mut out), - 0x8000_4002_u32 as Hresult - ); - assert!(out.is_null()); - assert_eq!((BLOB_VTABLE.add_ref)(this), 1); - assert_eq!((BLOB_VTABLE.release)(this), 1); - } - } - - #[derive(Default)] - struct MockModule { - object: Object, - frees: u32, - object_releases_at_free: u32, - } - - unsafe extern "system" fn mock_free(module: HMODULE) -> i32 { - // SAFETY: the test supplies a live MockModule and, when present, a - // live object whose first field is a MockHeader. - unsafe { - let module = &mut *module.cast::(); - module.frees += 1; - if !module.object.is_null() { - module.object_releases_at_free = (*module.object.cast::()).releases; - } - } - 1 - } - - #[test] - fn failed_validator_creation_frees_the_module() { - let mut module = MockModule::default(); - let handle = std::ptr::from_mut(&mut module).cast(); - // SAFETY: mock_free accepts this live mock module. - let outcome = - unsafe { Validator::from_module(handle, mock_free, |_| Err("creation failed".into())) }; - assert_eq!(outcome.err().as_deref(), Some("creation failed")); - assert_eq!(module.frees, 1); - } - - #[test] - fn dropping_validator_releases_the_object_before_freeing_the_module() { - let vtable = [0, 0, mock_release as *const () as usize]; - let mut object = Mock::new(&vtable, ()); - let object = object.object(); - let mut module = MockModule { - object, - ..MockModule::default() - }; - let handle = std::ptr::from_mut(&mut module).cast(); - // SAFETY: the mock module, interface and vtable outlive the validator. - let validator = - unsafe { Validator::from_module(handle, mock_free, |_| Ok(object)) }.unwrap(); - assert_eq!(module.frees, 0); - drop(validator); - assert_eq!(module.frees, 1); - assert_eq!(module.object_releases_at_free, 1); - } - - #[test] - fn load_error_has_no_trailing_nul() { - let missing = std::path::Path::new(r"Z:\nonexistent\victory_missing_dxil_test.dll"); - let err = Validator::load(Some(missing)).err().unwrap(); - assert!( - !err.contains('\0'), - "error string had trailing NUL: {err:?}" - ); - assert!(err.contains("victory_missing_dxil_test.dll")); - } - - #[test] - fn truncated_dxbc_container_is_rejected_before_calling_dxil() { - unsafe extern "system" fn panic_validate( - _: Object, - _: *mut Blob, - _: u32, - _: *mut Object, - ) -> Hresult { - panic!("IDxcValidator::Validate must not be called on malformed DXBC"); - } - let vtable = [ - 0, - 0, - mock_release as *const () as usize, - panic_validate as *const () as usize, - ]; - let mut validator_mock = Mock::new(&vtable, ()); - let mut validator = Validator { - object: validator_mock.object(), - _module: None, - }; - // Starts with "DXBC" magic but is truncated (< 32-byte header). - let mut truncated = b"DXBC\x00\x00\x00\x00".to_vec(); - assert!(validator.validate(&mut truncated).is_err()); - } -} diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 08c3503..f5c2014 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -3,7 +3,8 @@ //! //! Covers RDNA2 hardware semantics that differ from naive DXIL lowering: //! `v_med3_f32`/`v_med3_f16` with NaN operands, `v_fract_f32`/`v_fract_f16` -//! near `1.0`, and turn-range reduction for `v_sin_*`/`v_cos_*`. +//! near `1.0`, turn-range reduction for `v_sin_*`/`v_cos_*`, and the LDS +//! float atomics `ds_min_f32`/`ds_max_f32`. use super::host::{Dispatch, Host, Root, View}; use super::{HostShader, lower, validator}; @@ -43,9 +44,33 @@ const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 { /// VOP3 `op vdst, src0, src1, src2` (no modifiers). const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + vop3_mod(op, vdst, src0, src1, src2, 0, 0, 0, false) +} + +/// VOP3 `op vdst, src0, src1, src2` with explicit `abs`, `neg`, `omod`, `clamp`. +#[allow(clippy::too_many_arguments)] +const fn vop3_mod( + op: u16, + vdst: u8, + src0: u16, + src1: u16, + src2: u16, + abs: u8, + neg: u8, + omod: u8, + clamp: bool, +) -> [u32; 2] { [ - 0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32, - (src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18, + 0x35 << 26 + | (op as u32 & 0x3FF) << 16 + | (clamp as u32) << 15 + | (abs as u32 & 7) << 8 + | vdst as u32, + (neg as u32 & 7) << 29 + | (omod as u32 & 3) << 27 + | (src0 as u32 & 0x1FF) + | (src1 as u32 & 0x1FF) << 9 + | (src2 as u32 & 0x1FF) << 18, ] } @@ -69,11 +94,12 @@ const fn vgpr(n: u8) -> u16 { /// 4 dwords of root constants in `s0..s3`, runs `body` (leaving its result in /// `v0`), and stores `v0` to dword 0 of the raw UAV at heap index 0. fn build_valu_cs(body: &[u32]) -> HostShader { - build_valu_cs_threads(body, 1) + build_cs(body, 1, 0) } -/// The same compute harness with `threads` lanes per thread group. -fn build_valu_cs_threads(body: &[u32], threads: u32) -> HostShader { +/// [`build_valu_cs`] with `threads` threads in x (thread index in `v0` +/// on entry, before `body`) and `lds_bytes` of LDS (a multiple of 512). +fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { let mut words = Vec::new(); // s[4:5] = descriptor table address (heap index 0 -> byte offset 0). words.push(s_mov_b32(5, 0x80)); // inline constant 0 @@ -121,7 +147,7 @@ fn build_valu_cs_threads(body: &[u32], threads: u32) -> HostShader { slot: 1, }], io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + rsrc2: (5 << 1) | ((lds_bytes / 512) << 15), // 5 user SGPRs: s0..s4 threads: [threads, 1, 1], }), code, @@ -142,8 +168,6 @@ fn build_valu_cs_threads(body: &[u32], threads: u32) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - crumbs: None, - emulate_mesh: false, }) .expect("lower"); @@ -151,15 +175,12 @@ fn build_valu_cs_threads(body: &[u32], threads: u32) -> HostShader { stage: HwStage::Cs, dxil: lowered.dxil, user_data: lowered.user_data, - static_samplers: super::build_static_samplers(&lowered.samplers, &lowered.cmp_samplers), samplers: lowered.samplers, + static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, - address_map: lowered.address_map, - descriptor_words: lowered.descriptor_words, root_uavs: lowered.root_uavs, - root_indexed_views: Vec::new(), - mesh_emu: None, + root_indexed_views: res.root_indexed_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -189,17 +210,15 @@ fn run_cases( run_cases_on(shader, cases, &[("hardware", false), ("warp", true)], check); } -/// `run_cases` on the given backends only (WARP cannot pin a wave size, which -/// the lane-aware programs ask for). fn run_cases_on( shader: &HostShader, cases: &[[u32; 4]], - backends: &[(&str, bool)], + devices: &[(&str, bool)], mut check: impl FnMut(&str, usize, [u32; 4], u32), ) { let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut ran = 0; - for &(label, warp) in backends { + for &(label, warp) in devices { let Ok(host) = Host::new(warp) else { eprintln!("no SM 6.6 {label} device; skipped"); continue; @@ -232,57 +251,12 @@ fn run_cases_on( } ran += 1; } - assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); -} - -/// `run_cases_on`, but a backend whose driver rejects the pipeline is skipped -/// instead of failing the test. For shaders no available adapter can build — -/// the test then verifies nothing, which it reports. -fn run_cases_lenient( - shader: &HostShader, - cases: &[[u32; 4]], - backends: &[(&str, bool)], - mut check: impl FnMut(&str, usize, [u32; 4], u32), -) { - let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); - let mut ran = 0; - for &(label, warp) in backends { - 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 { - eprintln!("{label}: driver rejected the pipeline; skipped"); - continue; - }; - for (i, &inputs) in cases.iter().enumerate() { - let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; - for u in &shader.user_data { - ud[u.index as usize] = match (u.root, u.slot) { - (RootType::Constants, 0) => inputs[u.dword as usize], - (RootType::Table, 1) => 0, - other => panic!("unexpected user data {other:?}"), - }; - } - let out = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![(0, Root::Constants(ud))], - views: &[View::RawUav(1)], - samplers: &[], - groups: [1, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - check(label, i, inputs, out[0][0]); - } - ran += 1; - } - if ran == 0 { - eprintln!("no backend could build the pipeline; cases untested"); + if ran == 0 && devices.iter().all(|&(_, warp)| !warp) { + // A case for the hardware adapter alone, on a machine without one. + eprintln!("no SM 6.6 hardware device; a hardware-only case not run"); + return; } + assert!(ran > 0, "no SM 6.6 device available ({devices:?})"); } fn is_f16_nan(bits: u16) -> bool { @@ -385,17 +359,11 @@ fn v_cvt_f32_f64_rounds_to_nearest_even() { run_cases(&shader, &inputs, |backend, i, _, got| { let x = values[i]; if x.is_nan() { - assert!( - f32::from_bits(got).is_nan(), - "{backend}: cvt({x}) = {got:#010x}, want NaN" - ); + assert!(f32::from_bits(got).is_nan(), "{backend}: cvt({x}) = {got:#010x}, want NaN"); return; } let want = cvt_f32_f64_reference(x); - assert_eq!( - got, want, - "{backend}: cvt({x:e}) = {got:#010x}, want {want:#010x}" - ); + assert_eq!(got, want, "{backend}: cvt({x:e}) = {got:#010x}, want {want:#010x}"); }); } @@ -421,12 +389,6 @@ fn v_permlane16_and_x16_read_the_lanes_their_selectors_pick() { (0x89ab_cdef, 0x0123_4567), // reversed (0x1111_1111, 0xf0f0_f0f0), // repeats ]; - // Cross-lane code declares WaveSize(32), which WARP's pipeline creation - // refuses: the test is hardware-only, and skips where there is none. - if Host::new(false).is_err() { - eprintln!("no SM 6.6 hardware device; skipped"); - return; - } for (op, cross) in [(0x377u16, false), (0x378, true)] { for read in [0u8, 5, 15, 16, 22, 31] { let mut body = Vec::new(); @@ -434,23 +396,18 @@ fn v_permlane16_and_x16_read_the_lanes_their_selectors_pick() { // v_readlane_b32 s12, v1, read (inline constant 128 + read) body.extend_from_slice(&vop3(0x360, 12, vgpr(1), 128 + u16::from(read), 0)); body.push(vop1(0x001, 0, sgpr(12))); // v_mov_b32 v0, s12 - let shader = build_valu_cs_threads(&body, 32); + let shader = build_cs(&body, 32, 0); let inputs: Vec<[u32; 4]> = selectors.iter().map(|&(a, b)| [a, b, 0, 0]).collect(); // Cross-lane code declares WaveSize(32), which WARP's pipeline // creation refuses: hardware only. - run_cases_on( - &shader, - &inputs, - &[("hardware", false)], - |backend, i, inp, got| { - let want = permlane_source(u32::from(read), inp[0], inp[1], cross); - assert_eq!( - got, want, - "{backend}: op {op:#x} selectors {:08x?}, lane {read}", - selectors[i] - ); - }, - ); + run_cases_on(&shader, &inputs, &[("hardware", false)], |backend, i, inp, got| { + let want = permlane_source(u32::from(read), inp[0], inp[1], cross); + assert_eq!( + got, want, + "{backend}: op {op:#x} selectors {:08x?}, lane {read}", + selectors[i] + ); + }); } } } @@ -1062,6 +1019,286 @@ fn bfe_signed_and_unsigned_match_rdna2() { }); } +#[test] +fn f16_omod_applies_before_clamp() { + // VOP3 v_add_f16 (0x132 = 0x100 + VOP2 0x32): v0 = (v1 + v2) * omod [clamp] + let mul2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 1, false)); + let mul4 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 2, false)); + let div2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, false)); + let div2_clamp = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, true)); + + // f16 constants: 0.25=0x3400, 0.5=0x3800, 0.75=0x3A00, 1.0=0x3C00, 1.5=0x3E00, 2.0=0x4000, -0.5=0xB800 + run_cases( + &mul2, + &[[0x3400, 0x3800, 0, 0]], // (0.25 + 0.5) * 2 = 1.5 (0x3E00) + |backend, _, _, got| { + assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 mul:2"); + }, + ); + run_cases( + &mul4, + &[[0x3400, 0x3400, 0, 0]], // (0.25 + 0.25) * 4 = 2.0 (0x4000) + |backend, _, _, got| { + assert_eq!(got as u16, 0x4000, "{backend}: v_add_f16 mul:4"); + }, + ); + run_cases( + &div2, + &[[0x3E00, 0x3E00, 0, 0]], // (1.5 + 1.5) / 2 = 1.5 (0x3E00) + |backend, _, _, got| { + assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 div:2"); + }, + ); + // Ordering check: (0.75 + 0.75) = 1.5; div:2 before clamp gives 0.75 (0x3A00), + // whereas clamp before div:2 would give 0.5 (0x3800). + let clamp_cases: &[(u16, u16, u16)] = &[ + (0x3A00, 0x3A00, 0x3A00), // (0.75 + 0.75) / 2 = 0.75 -> 0.75 + (0x3E00, 0x3E00, 0x3C00), // (1.5 + 1.5) / 2 = 1.5 -> clamped to 1.0 + (0xB800, 0xB800, 0x0000), // (-0.5 + -0.5) / 2 = -0.5 -> clamped to 0.0 + ]; + let inputs: Vec<[u32; 4]> = clamp_cases + .iter() + .map(|&(a, b, _)| [u32::from(a), u32::from(b), 0, 0]) + .collect(); + run_cases(&div2_clamp, &inputs, |backend, i, _, got| { + let want = clamp_cases[i].2; + assert_eq!( + got as u16, want, + "{backend}: v_add_f16 div:2 clamp case {i}: got {:#06x}, want {want:#06x}", + got as u16, + ); + }); +} + +#[test] +fn cvt_16bit_int_from_f16_saturates_and_honors_modifiers() { + // VOP3 v_cvt_u16_f16 = 0x1D2 (0x180 + VOP1 0x52) + // VOP3 v_cvt_i16_f16 = 0x1D3 (0x180 + VOP1 0x53) + let cvt_u16 = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 0, 0, 0, false)); + let cvt_u16_abs = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 1, 0, 0, false)); + let cvt_i16 = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 0, 0, false)); + let cvt_i16_neg = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 1, 0, false)); + + let u16_cases: &[(u16, u16)] = &[ + (0xBC00, 0), // -1.0 -> 0 + (0xFC00, 0), // -inf -> 0 + (0x7E00, 0), // NaN -> 0 + (0x57BC, 123), // 123.75 -> 123 + (0x7BFF, 65504), // 65504.0 (max finite f16) -> 65504 + (0x7C00, 0xFFFF), // +inf -> 65535 (saturated) + ]; + let u16_in: Vec<[u32; 4]> = u16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); + run_cases(&cvt_u16, &u16_in, |backend, i, inp, got| { + let want = u16_cases[i].1; + assert_eq!( + got as u16, want, + "{backend}: v_cvt_u16_f16({:#06x}) = {:#06x}, want {want:#06x}", + inp[0], got as u16, + ); + }); + run_cases( + &cvt_u16_abs, + &[[0xD7BC, 0, 0, 0]], // |-123.75| -> 123 + |backend, _, _, got| { + assert_eq!(got as u16, 123, "{backend}: v_cvt_u16_f16 |src0|"); + }, + ); + + let i16_cases: &[(u16, u16)] = &[ + (0xFC00, 0x8000), // -inf -> -32768 + (0xF8E2, 0x8000), // -40000.0 -> -32768 (saturated, not wrapped) + (0xD7BC, (-123i16) as u16), // -123.75 -> -123 + (0x7E00, 0), // NaN -> 0 + (0x57BC, 123), // 123.75 -> 123 + (0x78E2, 0x7FFF), // +40000.0 -> 32767 (saturated, not wrapped) + (0x7C00, 0x7FFF), // +inf -> 32767 + ]; + let i16_in: Vec<[u32; 4]> = i16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); + run_cases(&cvt_i16, &i16_in, |backend, i, inp, got| { + let want = i16_cases[i].1; + assert_eq!( + got as u16, want, + "{backend}: v_cvt_i16_f16({:#06x}) = {:#06x}, want {want:#06x}", + inp[0], got as u16, + ); + }); + run_cases( + &cvt_i16_neg, + &[[0x57BC, 0, 0, 0], [0x78E2, 0, 0, 0]], // -(123.75) -> -123; -(40000.0) -> -32768 + |backend, i, _, got| { + let want = [(-123i16) as u16, 0x8000][i]; + assert_eq!(got as u16, want, "{backend}: v_cvt_i16_f16 -src0 case {i}"); + }, + ); +} + +const S_BARRIER: u32 = 0xBF8A_0000; + +/// VOP2 `op vdst, src0, vsrc1`. +const fn vop2(op: u8, vdst: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) +} + +/// DS `op vdst, addr, data0` at offset 0. +const fn ds(op: u8, vdst: u8, addr: u8, data0: u8) -> [u32; 2] { + [ + 0x36 << 26 | (op as u32) << 18, + (vdst as u32) << 24 | (data0 as u32) << 8 | addr as u32, + ] +} + +const DS_WRITE_B32: u8 = 0x0D; +const DS_MIN_F32: u8 = 0x12; +const DS_MAX_F32: u8 = 0x13; +const DS_MIN_RTN_F32: u8 = 0x32; +const DS_MAX_RTN_F32: u8 = 0x33; +const DS_READ_B32: u8 = 0x36; + +/// What RDNA2 writes for `ds_max_f32` / `ds_min_f32` over a dword holding +/// `old` with `data` (bits), as measured on gfx1036 with f32 denormals kept: +/// an sNaN, data first, then memory, is written quieted; otherwise a NaN +/// loses to a number (two quiet NaNs give the data); numbers compare as +/// floats with -0 below +0. +fn lds_min_max_ref(old: u32, data: u32, max: bool) -> u32 { + let nan = |x: u32| x & 0x7FFF_FFFF > 0x7F80_0000; + let snan = |x: u32| nan(x) && x & 0x40_0000 == 0; + let key = |x: u32| { + let b = x as i32; + if b < 0 { b ^ 0x7FFF_FFFF } else { b } + }; + if snan(data) { + return data | 0x40_0000; + } + if snan(old) { + return old | 0x40_0000; + } + match (nan(data), nan(old)) { + (true, true) | (false, true) => return data, + (true, false) => return old, + (false, false) => {} + } + let take = if max { + key(data) > key(old) + } else { + key(data) < key(old) + }; + if take { data } else { old } +} + +#[test] +fn ds_min_max_f32_order_floats_and_return_the_old_value() { + let values = [ + 0.0f32, + -0.0, + 1.0, + -1.0, + 2.5, + -2.5, + 1e-30, + -1e-30, + f32::from_bits(1), // denormal + f32::from_bits(0x8000_0001), + f32::INFINITY, + f32::NEG_INFINITY, + f32::MAX, + f32::MIN, + ]; + // Quiet and signalling NaNs of both signs, in memory and as data. + let nans = [ + 0x7FC0_0000u32, + 0xFFC0_0000, + 0x7F80_0001, + 0xFFA0_0000, + 0x7FBF_FFFF, + ]; + let bits: Vec = values.iter().map(|v| v.to_bits()).chain(nans).collect(); + let mut cases: Vec<[u32; 4]> = Vec::new(); + for &old in &bits { + for &data in &bits { + cases.push([old, data, 0, 0]); + } + } + for (rtn, plain, max, what) in [ + (DS_MAX_RTN_F32, DS_MAX_F32, true, "ds_max"), + (DS_MIN_RTN_F32, DS_MIN_F32, false, "ds_min"), + ] { + // v5 = 0; LDS[v5] = v1; the atomic with v2; v0 = the old value + // (rtn) or the dword afterwards (read back). + let mut returns_old = vec![vop1(0x001, 5, 0x80)]; + returns_old.extend(ds(DS_WRITE_B32, 0, 5, 1)); + returns_old.extend(ds(rtn, 0, 5, 2)); + let mut returns_new = vec![vop1(0x001, 5, 0x80)]; + returns_new.extend(ds(DS_WRITE_B32, 0, 5, 1)); + returns_new.extend(ds(plain, 0, 5, 2)); + returns_new.extend(ds(DS_READ_B32, 0, 5, 0)); + for (body, old_result) in [(returns_old, true), (returns_new, false)] { + // One thread with LDS declares WaveSize(32), which WARP's + // pipeline creation refuses: hardware only (the 64-thread test + // below runs on WARP too). + let shader = build_cs(&body, 1, 512); + run_cases_on( + &shader, + &cases, + &[("hardware", false)], + |backend, _, inp, got| { + let (old, data) = (f32::from_bits(inp[0]), f32::from_bits(inp[1])); + let want = if old_result { + inp[0] + } else { + lds_min_max_ref(inp[0], inp[1], max) + }; + assert_eq!( + got, + want, + "{backend}: {what}_f32 on {old:e} [{:#010x}] with {data:e} [{:#010x}] gave {got:#010x}, want {want:#010x} ({})", + inp[0], + inp[1], + if old_result { + "old value" + } else { + "dword after" + }, + ); + }, + ); + } + } +} + +#[test] +fn ds_min_max_f32_are_atomic_across_waves() { + // 64 threads (two host waves of 32 or one of 64): LDS[0] = v1, then + // every thread applies (thread - 32) as a float; v0 = LDS[0]. + for (op, max, init, want) in [ + (DS_MAX_F32, true, f32::NEG_INFINITY, 31.0f32), + (DS_MAX_F32, true, 100.0, 100.0), + (DS_MIN_F32, false, f32::INFINITY, -32.0), + (DS_MIN_F32, false, -0.0, -32.0), + ] { + let mut body = vec![vop1(0x001, 5, 0x80)]; + body.extend(ds(DS_WRITE_B32, 0, 5, 1)); + body.push(S_BARRIER); + body.push(vop2(0x26, 6, vgpr(0), 3)); // v_sub_nc_u32 v6, v0, v3 + body.push(vop1(0x005, 6, vgpr(6))); // v_cvt_f32_i32 + body.extend(ds(op, 0, 5, 6)); + body.push(S_BARRIER); + body.extend(ds(DS_READ_B32, 0, 5, 0)); + let shader = build_cs(&body, 64, 512); + run_cases( + &shader, + &[[init.to_bits(), 0, 32, 0]], + |backend, _, _, got| { + assert_eq!( + f32::from_bits(got), + want, + "{backend}: {} from {init} over 64 threads", + if max { "max" } else { "min" }, + ); + }, + ); + } +} + #[test] fn v_cmp_class_f16_matches_rdna2() { // v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6 @@ -1132,1002 +1369,142 @@ fn v_cmp_class_f16_matches_rdna2() { }); } -/// VOP2 `op vdst, src0, vsrc1`. -const fn vop2(op: u8, vdst: u8, src0: u16, vsrc1: u8) -> u32 { - (op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) -} - #[test] -fn v_ldexp_f16_matches_rdna2() { - // VOP2 `v_ldexp_f16 v0, v1, v2` (opcode 0x3b), preserving upper half from v3. - let vop2_cs = build_valu_cs(&[ - vop1(0x001, 0, vgpr(3)), // v_mov_b32 v0, v3 (sentinel upper half) - vop2(0x3b, 0, vgpr(1), 2), // v_ldexp_f16 v0, v1, v2 - ]); - // VOP3 `v_ldexp_f16 v0, |v1|, v2 clamp` (opcode 0x13b) with op_sel:[1, 0, 0, 1] - // (reads high half of v1, low half of v2, writes high half of v0). - let [mut w0, w1] = vop3(0x13b, 0, vgpr(1), vgpr(2), 0); - w0 |= (1 << 8) | (1 << 11) | (1 << 14) | (1 << 15); // abs[0], opsel[0], opsel[3], clamp - let vop3_cs = build_valu_cs(&[ - vop1(0x001, 0, vgpr(3)), // v_mov_b32 v0, v3 (sentinel lower half) - w0, - w1, - ]); - - let sentinel = 0xCAFE_0000u32; - // (f16 input, i16 exponent, expected f16 output) - let cases: &[(u16, i16, u16)] = &[ - (0x3C00, 0, 0x3C00), // 1.0 * 2^0 = 1.0 - (0x3E00, 3, 0x4A00), // 1.5 * 2^3 = 12.0 - (0xC200, -2, 0xBA00), // -3.0 * 2^-2 = -0.75 - (0x3C00, -15, 0x0200), // 1.0 * 2^-15 = f16 subnormal 0x0200 - (0x0001, 24, 0x3C00), // min f16 subnormal (2^-24) * 2^24 = 1.0 - (0x7BFF, 0, 0x7BFF), // max finite f16 * 2^0 stays 65504 (no premature inf) - (0x3C00, 16, 0x7C00), // 1.0 * 2^16 = 65536 -> +inf (RTE overflow) - (0xBC00, 1000, 0xFC00), // -1.0 * 2^1000 -> -inf - (0x0001, i16::MAX, 0x7C00), // min subnormal * 2^32767 -> +inf - (0x7BFF, i16::MIN, 0x0000), // max finite * 2^-32768 -> +0.0 - (0xFBFF, i16::MIN, 0x8000), // -max finite * 2^-32768 -> -0.0 - (0x0000, i16::MAX, 0x0000), // +0.0 * 2^32767 = +0.0 (not NaN) - (0x8000, i16::MAX, 0x8000), // -0.0 * 2^32767 = -0.0 (not NaN) - (0x7C00, i16::MIN, 0x7C00), // +inf * 2^-32768 = +inf (not NaN) - (0xFC00, i16::MIN, 0xFC00), // -inf * 2^-32768 = -inf (not NaN) +fn v_cvt_f32_f64_matches_ieee754() { + // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x00f -> VOP3 opcode 0x18f). + let plain = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]); + // Same with abs + neg on src0 (VOP3: abs[0] = bit 8 of w0, neg[0] = bit 29 of w1). + let [mut w0, mut w1] = vop3(0x18f, 0, vgpr(1), 0, 0); + w0 |= 1 << 8; + w1 |= 1 << 29; + let neg_abs = build_valu_cs(&[w0, w1]); + + let values: &[f64] = &[ + 0.0, + -0.0, + 1.0, + -1.0, + 3.5, + -123456.75, + // Tie-to-even: even mantissa stays, odd mantissa rounds up. + f64::from_bits(0x3FF0_0000_1000_0000), // 1.0 + 0.5 ulp(f32) -> 1.0 + f64::from_bits(0x3FF0_0000_3000_0000), // (1.0 + 1 ulp) + 0.5 ulp -> 1.0 + 2 ulp + f64::from_bits(0x3FF0_0000_1000_0001), // > 0.5 ulp -> rounds up + // Largest finite f32 and overflow to +Inf / -Inf. + f64::from(f32::MAX), + f64::from(f32::MAX) * 1.000_001, + -f64::from(f32::MAX) * 1.000_001, + 1e300, + // Subnormal range (exp64 in [874, 896]), including carry into smallest normal. + f64::from(f32::MIN_POSITIVE), + f64::from(f32::MIN_POSITIVE) * 0.5, + f64::from(f32::MIN_POSITIVE) * 0.75, + f64::from(f32::from_bits(0x007F_FFFF)), + f64::from_bits(0x380F_FFFF_F000_0000), // max subnormal + 0.5 ulp -> min normal + // exp64 == 873: exact 2^-150 ties to 0; strictly greater rounds to min subnormal (1). + f64::from_bits(0x3690_0000_0000_0000), + f64::from_bits(0x3690_0000_0000_0001), + f64::from_bits(0xB690_0000_0000_0001), + // Deep underflow -> +/-0.0. + 1e-200, + -1e-200, + // Infinities and NaNs. + f64::INFINITY, + f64::NEG_INFINITY, + f64::from_bits(0x7FF8_0000_0000_0000), // +qNaN + f64::from_bits(0x7FF0_0000_0000_0001), // +sNaN -> quieted ]; - let inputs: Vec<[u32; 4]> = cases + let inputs: Vec<[u32; 4]> = values .iter() - .map(|&(a, e, _)| [u32::from(a), u32::from(e as u16), sentinel, 0]) + .map(|&x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] + }) .collect(); - run_cases(&vop2_cs, &inputs, |backend, i, _, got| { - let (a, e, want_h) = cases[i]; - let want = sentinel | u32::from(want_h); - assert_eq!( - got, want, - "{backend}: v_ldexp_f16({a:#06x}, {e}) = {got:#010x}, want {want:#010x}", - ); - }); - - // NaN stays NaN (upper half preserved). - run_cases( - &vop2_cs, - &[[0x7E00, 4, sentinel, 0]], - |backend, _, _, got| { - assert_eq!(got & 0xFFFF_0000, sentinel); - let lo = (got & 0x7FFF) as u16; + run_cases(&plain, &inputs, |backend, i, _, got| { + let x = values[i]; + let want = (x as f32).to_bits(); + if x.is_nan() { assert!( - lo > 0x7C00, - "{backend}: v_ldexp_f16(NaN, 4) lo={lo:#06x}, want NaN" + f32::from_bits(got).is_nan() && (got & 0x0040_0000) != 0, + "{backend}: v_cvt_f32_f64({:#018x}) = {got:#010x}, expected qNaN", + x.to_bits(), + ); + } else { + assert_eq!( + got, want, + "{backend}: v_cvt_f32_f64({x} / {:#018x}) = {got:#010x}, want {want:#010x}", + x.to_bits(), ); - }, - ); - - // VOP3 abs[0] + opsel:[1,0,0,1] + clamp: - // |-0.25(=0xB400)| * 2^1 = 0.5 (0x3800) into high half; |-1.0(=0xBC00)| * 2^2 = 4.0 -> clamped 1.0 (0x3C00) - let lo_sentinel = 0x0000_1234u32; - let vop3_cases: &[([u32; 4], u32)] = &[ - ( - [0xB400_0000, 1, lo_sentinel, 0], - (0x3800u32 << 16) | lo_sentinel, - ), - ( - [0xBC00_0000, 2, lo_sentinel, 0], - (0x3C00u32 << 16) | lo_sentinel, - ), - ]; - let vop3_in: Vec<[u32; 4]> = vop3_cases.iter().map(|c| c.0).collect(); - run_cases(&vop3_cs, &vop3_in, |backend, i, _, got| { - let want = vop3_cases[i].1; - assert_eq!( - got, want, - "{backend}: v_ldexp_f16_e64 case {i} = {got:#010x}, want {want:#010x}", - ); - }); -} -#[test] -fn v_mad_16_and_int16_clamp_match_rdna2() { - let vop3_clamp = |op: u16, s0: u16, s1: u16, s2: u16, clamp: bool| { - let [mut w0, w1] = vop3(op, 0, s0, s1, s2); - if clamp { - w0 |= 1 << 15; } - [w0, w1] - }; - let with_sentinel = |words: [u32; 2]| { - build_valu_cs(&[ - vop1(0x001, 0, vgpr(4)), // v_mov_b32 v0, v4 (sentinel upper half) - words[0], - words[1], - ]) - }; - - // VOP3 opcodes: 0x303=v_add_nc_u16, 0x304=v_sub_nc_u16, 0x340=v_mad_u16, 0x35e=v_mad_i16. - let mad_u16_wrap = with_sentinel(vop3_clamp(0x340, vgpr(1), vgpr(2), vgpr(3), false)); - let mad_u16_sat = with_sentinel(vop3_clamp(0x340, vgpr(1), vgpr(2), vgpr(3), true)); - let mad_i16_wrap = with_sentinel(vop3_clamp(0x35e, vgpr(1), vgpr(2), vgpr(3), false)); - let mad_i16_sat = with_sentinel(vop3_clamp(0x35e, vgpr(1), vgpr(2), vgpr(3), true)); - let add_u16_sat = with_sentinel(vop3_clamp(0x303, vgpr(1), vgpr(2), 0, true)); - let sub_u16_sat = with_sentinel(vop3_clamp(0x304, vgpr(1), vgpr(2), 0, true)); - - let sentinel = 0xBEEF_0000u32; - - // v_mad_u16 wrapping & saturating (including u16::MAX * u16::MAX + u16::MAX without u32 wrap) - let u_cases: &[(u16, u16, u16, u16, u16)] = &[ - (20, 30, 40, 640, 640), - (300, 300, 100, (90_100u32 & 0xFFFF) as u16, u16::MAX), - (u16::MAX, u16::MAX, u16::MAX, 0, u16::MAX), - ]; - let u_in: Vec<[u32; 4]> = u_cases - .iter() - .map(|&(a, b, c, _, _)| [u32::from(a), u32::from(b), u32::from(c), sentinel]) - .collect(); - run_cases(&mad_u16_wrap, &u_in, |backend, i, _, got| { - let want = sentinel | u32::from(u_cases[i].3); - assert_eq!(got, want, "{backend}: v_mad_u16 wrap case {i}"); - }); - run_cases(&mad_u16_sat, &u_in, |backend, i, _, got| { - let want = sentinel | u32::from(u_cases[i].4); - assert_eq!(got, want, "{backend}: v_mad_u16 clamp case {i}"); }); - // v_mad_i16 wrapping & saturating (positive & negative overflow extremes) - let i_cases: &[(i16, i16, i16, i16, i16)] = &[ - (-10, 20, 50, -150, -150), - (i16::MIN, i16::MIN, i16::MAX, i16::MAX, i16::MAX), - (i16::MIN, i16::MAX, i16::MIN, 0, i16::MIN), - (200, 200, 100, (40_100i32 as i16), i16::MAX), - (-200, 200, -100, (-40_100i32 as i16), i16::MIN), - ]; - let i_in: Vec<[u32; 4]> = i_cases + // -|x| via VOP3 abs + neg modifiers. + let mod_values: &[f64] = &[2.5, -2.5, 0.0, f64::INFINITY]; + let mod_in: Vec<[u32; 4]> = mod_values .iter() - .map(|&(a, b, c, _, _)| { - [ - u32::from(a as u16), - u32::from(b as u16), - u32::from(c as u16), - sentinel, - ] + .map(|&x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] }) .collect(); - run_cases(&mad_i16_wrap, &i_in, |backend, i, _, got| { - let want = sentinel | u32::from(i_cases[i].3 as u16); - assert_eq!(got, want, "{backend}: v_mad_i16 wrap case {i}"); - }); - run_cases(&mad_i16_sat, &i_in, |backend, i, _, got| { - let want = sentinel | u32::from(i_cases[i].4 as u16); - assert_eq!(got, want, "{backend}: v_mad_i16 clamp case {i}"); + run_cases(&neg_abs, &mod_in, |backend, i, _, got| { + let x = mod_values[i]; + let want = (-(x.abs()) as f32).to_bits(); + assert_eq!( + got, want, + "{backend}: v_cvt_f32_f64(-|{x}|) = {got:#010x}, want {want:#010x}", + ); }); - - // v_add_nc_u16 clamp & v_sub_nc_u16 clamp - run_cases( - &add_u16_sat, - &[[60000, 10000, 0, sentinel], [123, 456, 0, sentinel]], - |backend, i, _, got| { - let want = sentinel | [u32::from(u16::MAX), 579][i]; - assert_eq!(got, want, "{backend}: v_add_nc_u16 clamp case {i}"); - }, - ); - run_cases( - &sub_u16_sat, - &[[5, 10, 0, sentinel], [500, 200, 0, sentinel]], - |backend, i, _, got| { - let want = sentinel | [0, 300][i]; - assert_eq!(got, want, "{backend}: v_sub_nc_u16 clamp case {i}"); - }, - ); } + #[test] -fn v_sad_family_matches_rdna2() { - let vop3_clamp = |op: u16| -> [u32; 2] { - let [mut w0, w1] = vop3(op, 0, vgpr(1), vgpr(2), vgpr(3)); - w0 |= 1 << 15; // clamp = 1 - [w0, w1] +fn whole_wave_f64_sum_and_cvt_f32_f64() { + let s_or_saveexec_b32 = + |sdst: u8, src0: u8| 0xBE80_0000 | (sdst as u32) << 16 | 0x3D << 8 | src0 as u32; + let v_mov_dpp8 = |vdst: u8, vsrc: u8, sel: u32| [vop1(0x001, vdst, 0xE9), vsrc as u32 | (sel << 8)]; + let v_mov_row_mirror = |vdst: u8, vsrc: u8| { + [ + vop1(0x001, vdst, 0xFA), + vsrc as u32 | (0x140 << 8) | (1 << 19) | (0xF << 24) | (0xF << 28), + ] }; - // v_sad_u8 (0x15a) - let sad_u8 = build_valu_cs(&vop3(0x15a, 0, vgpr(1), vgpr(2), vgpr(3))); - let sad_u8_clamp = build_valu_cs(&vop3_clamp(0x15a)); - // Bytes: |0x10-0x20|=16, |0xFF-0x00|=255, |0x05-0x05|=0, |0x80-0x70|=16 -> sum = 287 - run_cases( - &sad_u8, - &[ - [0x8005_FF10, 0x7005_0020, 100, 0], - [0xFFFF_FFFF, 0x0000_0000, u32::MAX - 10, 0], // wraps: (2^32 - 11) + 1020 = 1009 - ], - |backend, i, _, got| { - let want = [387u32, 1009][i]; - assert_eq!(got, want, "{backend}: v_sad_u8 case {i}"); - }, - ); - run_cases( - &sad_u8_clamp, - &[[0xFFFF_FFFF, 0x0000_0000, u32::MAX - 10, 0]], // saturates to u32::MAX - |backend, _, _, got| { - assert_eq!(got, u32::MAX, "{backend}: v_sad_u8 clamp"); - }, - ); - - // v_msad_u8 (0x171): zero bytes in src0 contribute 0 regardless of src1. - let msad_u8 = build_valu_cs(&vop3(0x171, 0, vgpr(1), vgpr(2), vgpr(3))); - // Byte 0: src0=0x00 -> skipped (even though src1=0xFF) - // Byte 1: |0x10-0x00| = 16 (src1=0 is NOT skipped!) - // Byte 2: src0=0x00 -> skipped - // Byte 3: |0x80-0x70| = 16 -> sum = 32 - run_cases( - &msad_u8, - &[[0x8000_1000, 0x70AA_00FF, 5, 0]], - |backend, _, _, got| { - assert_eq!(got, 37, "{backend}: v_msad_u8"); - }, - ); - - // v_sad_u16 (0x15c) - let sad_u16 = build_valu_cs(&vop3(0x15c, 0, vgpr(1), vgpr(2), vgpr(3))); - let sad_u16_clamp = build_valu_cs(&vop3_clamp(0x15c)); - // Low: |0x0100 - 0x0300| = 0x200; High: |0xFFFF - 0x0001| = 0xFFFE -> sum = 0x101FE - run_cases( - &sad_u16, - &[[0xFFFF_0100, 0x0001_0300, 2, 0]], - |backend, _, _, got| { - assert_eq!(got, 0x10200, "{backend}: v_sad_u16"); - }, - ); - run_cases( - &sad_u16_clamp, - &[[0xFFFF_FFFF, 0x0000_0000, u32::MAX - 5, 0]], - |backend, _, _, got| { - assert_eq!(got, u32::MAX, "{backend}: v_sad_u16 clamp"); - }, - ); - - // v_sad_u32 (0x15d) - let sad_u32 = build_valu_cs(&vop3(0x15d, 0, vgpr(1), vgpr(2), vgpr(3))); - let sad_u32_clamp = build_valu_cs(&vop3_clamp(0x15d)); - run_cases( - &sad_u32, - &[ - [10, 30, 5, 0], - [0xFFFF_FFFF, 0, 10, 0], // wraps: (2^32 - 1) + 10 = 9 - ], - |backend, i, _, got| { - let want = [25u32, 9][i]; - assert_eq!(got, want, "{backend}: v_sad_u32 case {i}"); - }, - ); - run_cases( - &sad_u32_clamp, - &[[0xFFFF_FFFF, 0, 10, 0]], - |backend, _, _, got| { - assert_eq!(got, u32::MAX, "{backend}: v_sad_u32 clamp"); - }, - ); -} - -#[test] -fn v_frexp_f32_and_f16_match_rdna2() { - // VOP1 opcodes: 0x3f=v_frexp_exp_i32_f32, 0x40=v_frexp_mant_f32, - // 0x59=v_frexp_mant_f16, 0x5a=v_frexp_exp_i16_f16. - let exp_f32 = build_valu_cs(&[vop1(0x3f, 0, vgpr(1))]); - let mant_f32 = build_valu_cs(&[vop1(0x40, 0, vgpr(1))]); - // For f16 tests, initialize v0 = 0xDEAD_0000 so we also verify high-half preservation. - let mant_f16 = build_valu_cs(&[ - vop1(0x001, 0, vgpr(2)), // v_mov_b32 v0, v2 (sentinel upper half) - vop1(0x59, 0, vgpr(1)), - ]); - let exp_f16 = build_valu_cs(&[ - vop1(0x001, 0, vgpr(2)), // v_mov_b32 v0, v2 (sentinel upper half) - vop1(0x5a, 0, vgpr(1)), - ]); - - // (input f32 bits, expected mantissa f32 bits, expected i32 exponent) - let f32_cases: &[(u32, u32, i32)] = &[ - (0.0f32.to_bits(), 0.0f32.to_bits(), 0), - ((-0.0f32).to_bits(), (-0.0f32).to_bits(), 0), - (0.5f32.to_bits(), 0.5f32.to_bits(), 0), - (1.0f32.to_bits(), 0.5f32.to_bits(), 1), - ((-6.0f32).to_bits(), (-0.75f32).to_bits(), 3), - (0.125f32.to_bits(), 0.5f32.to_bits(), -2), - (f32::INFINITY.to_bits(), f32::INFINITY.to_bits(), 0), - (f32::NEG_INFINITY.to_bits(), f32::NEG_INFINITY.to_bits(), 0), - // Subnormals: 2^-127 = 0.5 * 2^-126; 3 * 2^-149 = 0.75 * 2^-147; -2^-149 = -0.5 * 2^-148 - (0x0040_0000, 0.5f32.to_bits(), -126), - (0x0000_0003, 0.75f32.to_bits(), -147), - (0x8000_0001, (-0.5f32).to_bits(), -148), - ]; - let f32_in: Vec<[u32; 4]> = f32_cases.iter().map(|&(x, _, _)| [x, 0, 0, 0]).collect(); - run_cases(&mant_f32, &f32_in, |backend, i, inp, got| { - let want = f32_cases[i].1; - assert_eq!( - got, want, - "{backend}: v_frexp_mant_f32({:#010x}) = {got:#010x}, want {want:#010x}", - inp[0], - ); - }); - run_cases(&exp_f32, &f32_in, |backend, i, inp, got| { - let want = f32_cases[i].2 as u32; - assert_eq!( - got, want, - "{backend}: v_frexp_exp_i32_f32({:#010x}) = {} ({got:#010x}), want {}", - inp[0], got as i32, f32_cases[i].2, - ); - }); - - // NaN: mantissa stays NaN, exponent is 0. - let qnan = 0x7FC0_0000u32; - run_cases(&mant_f32, &[[qnan, 0, 0, 0]], |backend, _, _, got| { - assert!( - f32::from_bits(got).is_nan(), - "{backend}: v_frexp_mant_f32(NaN) = {got:#010x}, want NaN", - ); - }); - run_cases(&exp_f32, &[[qnan, 0, 0, 0]], |backend, _, _, got| { - assert_eq!( - got, 0, - "{backend}: v_frexp_exp_i32_f32(NaN) = {got}, want 0" - ); - }); - - // f16 cases: (input f16, expected mantissa f16, expected i16 exponent) - // 0x0000=+0, 0x8000=-0, 0x3800=0.5, 0x3C00=1.0, 0xC600=-6.0 (-0.75 * 2^3, -0.75=0xBA00), - // 0x7BFF=65504 (max f16 -> mant=0x3BFF, exp=16), 0x0001=2^-24 (min subnormal -> 0.5 * 2^-23), - // 0x8003=-3*2^-24 (-0.75 * 2^-22), 0x7C00=+inf, 0xFC00=-inf. - let sentinel = 0xDEAD_0000u32; - let f16_cases: &[(u16, u16, i16)] = &[ - (0x0000, 0x0000, 0), - (0x8000, 0x8000, 0), - (0x3800, 0x3800, 0), - (0x3C00, 0x3800, 1), - (0xC600, 0xBA00, 3), - (0x7BFF, 0x3BFF, 16), - (0x0001, 0x3800, -23), - (0x8003, 0xBA00, -22), - (0x7C00, 0x7C00, 0), - (0xFC00, 0xFC00, 0), - ]; - let f16_in: Vec<[u32; 4]> = f16_cases - .iter() - .map(|&(x, _, _)| [u32::from(x), sentinel, 0, 0]) - .collect(); - run_cases(&mant_f16, &f16_in, |backend, i, inp, got| { - let want = sentinel | u32::from(f16_cases[i].1); - assert_eq!( - got, want, - "{backend}: v_frexp_mant_f16({:#06x}) = {got:#010x}, want {want:#010x}", - inp[0], - ); - }); - run_cases(&exp_f16, &f16_in, |backend, i, inp, got| { - let want = sentinel | u32::from(f16_cases[i].2 as u16); - assert_eq!( - got, want, - "{backend}: v_frexp_exp_i16_f16({:#06x}) = {got:#010x}, want {want:#010x}", - inp[0], - ); - }); - - // f16 NaN: mantissa is f16 NaN (upper half preserved), exponent is 0. - run_cases( - &mant_f16, - &[[0x7E00, sentinel, 0, 0]], - |backend, _, _, got| { - assert_eq!(got & 0xFFFF_0000, sentinel); - let lo = (got & 0x7FFF) as u16; - assert!( - lo > 0x7C00, - "{backend}: v_frexp_mant_f16(NaN) lo={lo:#06x}, want NaN" - ); - }, - ); - run_cases( - &exp_f16, - &[[0x7E00, sentinel, 0, 0]], - |backend, _, _, got| { - assert_eq!( - got, sentinel, - "{backend}: v_frexp_exp_i16_f16(NaN) = {got:#010x}, want 0" - ); - }, - ); -} - -#[test] -fn v_div_fixup_f32_matches_rdna2() { - // VOP3 v_div_fixup_f32 v0, v1 (quot), v2 (denom), v3 (num) — opcode 0x15f - let shader = build_valu_cs(&vop3(0x15f, 0, vgpr(1), vgpr(2), vgpr(3))); - let p_zero = 0.0f32.to_bits(); - let n_zero = (-0.0f32).to_bits(); - let p_inf = f32::INFINITY.to_bits(); - let n_inf = f32::NEG_INFINITY.to_bits(); - let qnan = 0x7FC0_0000u32; - let snan1 = 0x7F80_0001u32; - let snan2 = 0x7F80_0002u32; - let f_pos = 3.5f32.to_bits(); - let f_neg = (-3.5f32).to_bits(); - let two = 2.0f32.to_bits(); - let m_two = (-2.0f32).to_bits(); - let seven = 7.0f32.to_bits(); - let m_seven = (-7.0f32).to_bits(); - - // (quot, denom, num) -> expected exact bits (None = any NaN) - let cases: &[([u32; 4], Option)] = &[ - // Normal quotients: sign = sign(denom) ^ sign(num). - ([f_pos, two, seven, 0], Some(f_pos)), - ([f_pos, m_two, seven, 0], Some(f_neg)), - ([f_neg, m_two, m_seven, 0], Some(f_pos)), - // NaN quotient with finite non-zero denom/num -> ±inf with sign_out. - ([qnan, two, seven, 0], Some(p_inf)), - ([qnan, m_two, seven, 0], Some(n_inf)), - // Division by ±0 -> ±inf with sign_out. - ([f_pos, p_zero, seven, 0], Some(p_inf)), - ([f_pos, n_zero, seven, 0], Some(n_inf)), - ([f_pos, n_zero, m_seven, 0], Some(p_inf)), - // ±inf / finite -> ±inf with sign_out. - ([f_pos, m_two, p_inf, 0], Some(n_inf)), - ([f_pos, m_two, n_inf, 0], Some(p_inf)), - // finite / ±inf and ±0 / finite -> ±0.0 with sign_out. - ([f_pos, n_inf, seven, 0], Some(n_zero)), - ([f_pos, n_inf, m_seven, 0], Some(p_zero)), - ([f_pos, m_two, p_zero, 0], Some(n_zero)), - ([f_pos, m_two, n_zero, 0], Some(p_zero)), - // Indeterminate forms: 0/0 and inf/inf -> qNaN. - ([f_pos, p_zero, p_zero, 0], None), - ([f_pos, n_zero, p_zero, 0], None), - ([f_pos, p_inf, n_inf, 0], None), - // NaN in denom or num propagates quieted NaN (denom takes priority). - ([f_pos, snan1, snan2, 0], Some(0x7FC0_0001)), - ([f_pos, two, snan2, 0], Some(0x7FC0_0002)), - ]; - let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); - run_cases(&shader, &inputs, |backend, i, inp, got| match cases[i].1 { - Some(want) => assert_eq!( - got, want, - "{backend}: v_div_fixup_f32({:#010x}, {:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}", - inp[0], inp[1], inp[2], - ), - None => assert!( - f32::from_bits(got).is_nan(), - "{backend}: v_div_fixup_f32({:#010x}, {:#010x}, {:#010x}) = {got:#010x}, want NaN", - inp[0], - inp[1], - inp[2], - ), - }); -} - -#[test] -fn v_div_fixup_f16_matches_rdna2() { - // VOP3 v_div_fixup_f16 v0, v1 (quot), v2 (denom), v3 (num) — opcode 0x35f - let shader = build_valu_cs(&vop3(0x35f, 0, vgpr(1), vgpr(2), vgpr(3))); - // f16 bit patterns: +0=0x0000, -0=0x8000, +1=0x3C00, -2=0xC000, +3.5=0x4300, -3.5=0xC300, - // +inf=0x7C00, -inf=0xFC00, qNaN=0x7E00 - let cases: &[([u32; 4], Option)] = &[ - ([0x4300, 0xC000, 0x3C00, 0], Some(0xC300)), // copysign(3.5, -2 ^ +1) = -3.5 - ([0xC300, 0xC000, 0xBC00, 0], Some(0x4300)), // copysign(-3.5, -2 ^ -1) = +3.5 - ([0x7E00, 0xC000, 0x3C00, 0], Some(0xFC00)), // NaN quot -> -inf - ([0x4300, 0x8000, 0x3C00, 0], Some(0xFC00)), // +1 / -0 -> -inf - ([0x4300, 0xFC00, 0x3C00, 0], Some(0x8000)), // +1 / -inf -> -0.0 - ([0x4300, 0xC000, 0x0000, 0], Some(0x8000)), // +0 / -2 -> -0.0 - ([0x4300, 0x0000, 0x0000, 0], None), // 0 / 0 -> NaN - ([0x4300, 0x7C00, 0xFC00, 0], None), // -inf / +inf -> NaN - ([0x4300, 0x7E00, 0x3C00, 0], None), // NaN denom -> NaN - ]; - let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); - run_cases(&shader, &inputs, |backend, i, inp, got| { - let got_h = got as u16; - match cases[i].1 { - Some(want) => assert_eq!( - got_h, want, - "{backend}: v_div_fixup_f16({:#06x}, {:#06x}, {:#06x}) = {got_h:#06x}, want {want:#06x}", - inp[0], inp[1], inp[2], - ), - None => assert!( - is_f16_nan(got_h), - "{backend}: v_div_fixup_f16({:#06x}, {:#06x}, {:#06x}) = {got_h:#06x}, want NaN", - inp[0], - inp[1], - inp[2], - ), - } - }); -} - -#[test] -fn v_pk_int16_clamp_saturates_as_rdna2() { - let pack_u = |lo: u16, hi: u16| u32::from(lo) | (u32::from(hi) << 16); - let pack_i = |lo: i16, hi: i16| pack_u(lo as u16, hi as u16); - - // VOP3P opcodes: 0x00=mad_i16, 0x02=add_i16, 0x03=sub_i16, 0x09=mad_u16, 0x0a=add_u16, 0x0b=sub_u16. - let add_u16 = build_valu_cs(&vop3p(0x0a, 0, vgpr(1), vgpr(2), 0, true)); - let sub_u16 = build_valu_cs(&vop3p(0x0b, 0, vgpr(1), vgpr(2), 0, true)); - let mad_u16 = build_valu_cs(&vop3p(0x09, 0, vgpr(1), vgpr(2), vgpr(3), true)); - let add_i16 = build_valu_cs(&vop3p(0x02, 0, vgpr(1), vgpr(2), 0, true)); - let sub_i16 = build_valu_cs(&vop3p(0x03, 0, vgpr(1), vgpr(2), 0, true)); - let mad_i16 = build_valu_cs(&vop3p(0x00, 0, vgpr(1), vgpr(2), vgpr(3), true)); - - // add_u16 clamp: lo overflows (60000+10000 -> 65535), hi fits (100+200 -> 300) - run_cases( - &add_u16, - &[ - [pack_u(60000, 100), pack_u(10000, 200), 0, 0], - [pack_u(u16::MAX, 0), pack_u(u16::MAX, 0), 0, 0], - ], - |backend, i, _, got| { - let want = [pack_u(u16::MAX, 300), pack_u(u16::MAX, 0)][i]; - assert_eq!(got, want, "{backend}: v_pk_add_u16 clamp case {i}"); - }, - ); - - // sub_u16 clamp: lo underflows (5-10 -> 0), hi fits (500-200 -> 300) - run_cases( - &sub_u16, - &[ - [pack_u(5, 500), pack_u(10, 200), 0, 0], - [pack_u(0, u16::MAX), pack_u(u16::MAX, 0), 0, 0], - ], - |backend, i, _, got| { - let want = [pack_u(0, 300), pack_u(0, u16::MAX)][i]; - assert_eq!(got, want, "{backend}: v_pk_sub_u16 clamp case {i}"); - }, - ); - - // mad_u16 clamp: lo max*max+max -> 65535 (tests no u32 wrap!), hi 20*30+40 -> 640 - run_cases( - &mad_u16, - &[[ - pack_u(u16::MAX, 20), - pack_u(u16::MAX, 30), - pack_u(u16::MAX, 40), - 0, - ]], - |backend, _, _, got| { - let want = pack_u(u16::MAX, 640); - assert_eq!(got, want, "{backend}: v_pk_mad_u16 clamp"); - }, - ); - - // add_i16 clamp: lo +overflow (30000+10000 -> 32767), hi -overflow (-30000-10000 -> -32768) - run_cases( - &add_i16, - &[ - [pack_i(30000, -30000), pack_i(10000, -10000), 0, 0], - [pack_i(100, -50), pack_i(-25, 20), 0, 0], - ], - |backend, i, _, got| { - let want = [pack_i(i16::MAX, i16::MIN), pack_i(75, -30)][i]; - assert_eq!(got, want, "{backend}: v_pk_add_i16 clamp case {i}"); - }, - ); - - // sub_i16 clamp: lo -overflow (-30000-10000 -> -32768), hi +overflow (30000-(-10000) -> 32767) - run_cases( - &sub_i16, - &[ - [pack_i(-30000, 30000), pack_i(10000, -10000), 0, 0], - [pack_i(0, -100), pack_i(i16::MIN, -200), 0, 0], - ], - |backend, i, _, got| { - let want = [pack_i(i16::MIN, i16::MAX), pack_i(i16::MAX, 100)][i]; - assert_eq!(got, want, "{backend}: v_pk_sub_i16 clamp case {i}"); - }, - ); - - // mad_i16 clamp: lo (-32768)*(-32768)+32767 -> 32767, hi (-32768)*(32767)-32768 -> -32768 - run_cases( - &mad_i16, - &[ - [ - pack_i(i16::MIN, i16::MIN), - pack_i(i16::MIN, i16::MAX), - pack_i(i16::MAX, i16::MIN), - 0, - ], - [pack_i(-10, 5), pack_i(20, -4), pack_i(50, -3), 0], - ], - |backend, i, _, got| { - let want = [pack_i(i16::MAX, i16::MIN), pack_i(-150, -23)][i]; - assert_eq!(got, want, "{backend}: v_pk_mad_i16 clamp case {i}"); - }, - ); -} - -#[test] -fn v_pk_fmac_f16_matches_rdna2() { - // VOP2 `v_pk_fmac_f16 v0, v1, v2` (opcode 0x3c), initialized from v3 (root constant s2). - let vop2_cs = build_valu_cs(&[ - vop1(0x001, 0, vgpr(3)), // v_mov_b32 v0, v3 (accumulator) - vop2(0x3c, 0, vgpr(1), 2), // v_pk_fmac_f16 v0, v1, v2 - ]); - // VOP2 with inline constant 1.0 (0xF2): GFX10 puts 1.0 in lo f16 and 0.0 in hi f16. - let vop2_inline_cs = build_valu_cs(&[ - vop1(0x001, 0, vgpr(3)), // v_mov_b32 v0, v3 - vop2(0x3c, 0, 0xF2, 2), // v_pk_fmac_f16 v0, 1.0, v2 - ]); - // VOP3 `v_pk_fmac_f16 v0, |v1|, -v2 clamp` (opcode 0x13c): abs[0], neg[1], clamp. - let [mut w0, mut w1] = vop3(0x13c, 0, vgpr(1), vgpr(2), 0); - w0 |= (1 << 8) | (1 << 15); // abs[0], clamp - w1 |= 1 << 30; // neg[1] - let vop3_mod_cs = build_valu_cs(&[ - vop1(0x001, 0, vgpr(3)), // v_mov_b32 v0, v3 - w0, - w1, - ]); - - let pack = |lo: u16, hi: u16| u32::from(lo) | (u32::from(hi) << 16); - // f16 constants: 0.0=0x0000, 0.5=0x3800, 1.0=0x3C00, 2.0=0x4000, 3.0=0x4200, - // 4.0=0x4400, 5.0=0x4500, 7.0=0x4700, 10.0=0x4900, -2.0=0xC000, -3.0=0xC200. - let vop2_cases: &[([u32; 4], u32)] = &[ - // lo: 2.0 * 3.0 + 1.0 = 7.0; hi: -2.0 * 4.0 + 10.0 = 2.0 - ( - [ - pack(0x4000, 0xC000), - pack(0x4200, 0x4400), - pack(0x3C00, 0x4900), - 0, - ], - pack(0x4700, 0x4000), - ), - // lo: 0.5 * 4.0 + 3.0 = 5.0; hi: 0.0 * 7.0 + (-3.0) = -3.0 - ( - [ - pack(0x3800, 0x0000), - pack(0x4400, 0x4700), - pack(0x4200, 0xC200), - 0, - ], - pack(0x4500, 0xC200), - ), - ]; - let vop2_in: Vec<[u32; 4]> = vop2_cases.iter().map(|c| c.0).collect(); - run_cases(&vop2_cs, &vop2_in, |backend, i, inp, got| { - let want = vop2_cases[i].1; - assert_eq!( - got, want, - "{backend}: v_pk_fmac_f16({:#010x}, {:#010x}, acc={:#010x}) = {got:#010x}, want {want:#010x}", - inp[0], inp[1], inp[2], - ); - }); - - // Inline 1.0: lo = 1.0 * 3.0 + 2.0 = 5.0; hi = 0.0 * 4.0 + 7.0 = 7.0 (unchanged). - run_cases( - &vop2_inline_cs, - &[[0, pack(0x4200, 0x4400), pack(0x4000, 0x4700), 0]], - |backend, _, _, got| { - let want = pack(0x4500, 0x4700); - assert_eq!( - got, want, - "{backend}: v_pk_fmac_f16(1.0, ...) = {got:#010x}, want {want:#010x}", - ); - }, - ); - - // VOP3 abs[0], neg[1], clamp: - // lo: |-2.0| * (-0.5) + 1.5(=0x3E00) = 0.5 (in [0, 1]) -> 0x3800 - // hi: |-2.0| * (-2.0) + 1.0 = -3.0 -> clamped to 0.0 (0x0000) - // case 2: lo: |-2.0| * (-(-1.0)) + 0.5 = 2.5 -> clamped to 1.0 (0x3C00) - // hi: |0.5| * (-(-0.5)) + 0.25(=0x3400) = 0.5 (0x3800) - let vop3_cases: &[([u32; 4], u32)] = &[ - ( - [ - pack(0xC000, 0xC000), - pack(0x3800, 0x4000), - pack(0x3E00, 0x3C00), - 0, - ], - pack(0x3800, 0x0000), - ), - ( - [ - pack(0xC000, 0x3800), - pack(0xBC00, 0xB800), - pack(0x3800, 0x3400), - 0, - ], - pack(0x3C00, 0x3800), - ), - ]; - let vop3_in: Vec<[u32; 4]> = vop3_cases.iter().map(|c| c.0).collect(); - run_cases(&vop3_mod_cs, &vop3_in, |backend, i, inp, got| { - let want = vop3_cases[i].1; - assert_eq!( - got, want, - "{backend}: v_pk_fmac_f16_e64(|{:#010x}|, -{:#010x}, acc={:#010x}) clamp = {got:#010x}, want {want:#010x}", - inp[0], inp[1], inp[2], - ); - }); -} - -#[test] -fn signed_scalar_add_sub_scc_matches_rdna2() { - // s_add_i32 s6, s0, s1 (SOP2 0x02); s_cselect_b32 s7, 1, 0 (SOP2 0x0A); v_mov_b32 v0, s7 - let add_scc = build_valu_cs(&[ - sop2(0x02, 6, 0, 1), - sop2(0x0A, 7, 0x81, 0x80), - vop1(0x001, 0, sgpr(7)), - ]); - // s_sub_i32 s6, s0, s1 (SOP2 0x03); s_cselect_b32 s7, 1, 0; v_mov_b32 v0, s7 - let sub_scc = build_valu_cs(&[ - sop2(0x03, 6, 0, 1), - sop2(0x0A, 7, 0x81, 0x80), - vop1(0x001, 0, sgpr(7)), - ]); - // s_mov_b32 s6, s0; s_addk_i32 s6, +1 (SOPK 0x0F); s_cselect_b32 s7, 1, 0; v_mov_b32 v0, s7 - let addk_pos1 = build_valu_cs(&[ - s_mov_b32(6, 0), - sopk(0x0F, 6, 1), - sop2(0x0A, 7, 0x81, 0x80), - vop1(0x001, 0, sgpr(7)), - ]); - // s_mov_b32 s6, s0; s_addk_i32 s6, -32768 (SOPK 0x0F); s_cselect_b32 s7, 1, 0; v_mov_b32 v0, s7 - let addk_neg_min = build_valu_cs(&[ - s_mov_b32(6, 0), - sopk(0x0F, 6, i16::MIN), - sop2(0x0A, 7, 0x81, 0x80), - vop1(0x001, 0, sgpr(7)), - ]); - - let add_cases: &[(i32, i32)] = &[ - (0, 0), - (10, 20), - (-1, 1), // unsigned carry, no signed overflow - (i32::MAX, 0), - (i32::MAX, 1), // positive overflow - (i32::MAX, i32::MAX), // positive overflow - (i32::MIN, 0), - (i32::MIN, -1), // negative overflow - (i32::MIN, i32::MIN), // negative overflow (result 0) - (i32::MIN, i32::MAX), // -1, no overflow - ]; - let add_in: Vec<[u32; 4]> = add_cases - .iter() - .map(|&(a, b)| [a as u32, b as u32, 0, 0]) - .collect(); - run_cases(&add_scc, &add_in, |backend, i, _, got| { - let (a, b) = add_cases[i]; - let want = u32::from(a.overflowing_add(b).1); - assert_eq!( - got, want, - "{backend}: s_add_i32({a}, {b}) SCC = {got}, want {want}", - ); - }); - - let sub_cases: &[(i32, i32)] = &[ - (0, 0), - (0, 1), // unsigned borrow, no signed overflow - (0, i32::MIN), // 0 - (-2^31) overflows i32 - (i32::MIN, 0), - (i32::MIN, 1), // negative overflow - (i32::MIN, i32::MIN), // 0, no overflow - (i32::MAX, -1), // positive overflow - (i32::MAX, i32::MIN), // positive overflow - (-5, -3), // -2, no overflow - (-1, i32::MAX), // -2^31 (i32::MIN), no overflow - ]; - let sub_in: Vec<[u32; 4]> = sub_cases - .iter() - .map(|&(a, b)| [a as u32, b as u32, 0, 0]) - .collect(); - run_cases(&sub_scc, &sub_in, |backend, i, _, got| { - let (a, b) = sub_cases[i]; - let want = u32::from(a.overflowing_sub(b).1); - assert_eq!( - got, want, - "{backend}: s_sub_i32({a}, {b}) SCC = {got}, want {want}", - ); - }); - - let addk_pos_cases: &[i32] = &[0, -1, i32::MAX - 1, i32::MAX, i32::MIN]; - let addk_pos_in: Vec<[u32; 4]> = addk_pos_cases - .iter() - .map(|&a| [a as u32, 0, 0, 0]) - .collect(); - run_cases(&addk_pos1, &addk_pos_in, |backend, i, _, got| { - let a = addk_pos_cases[i]; - let want = u32::from(a.overflowing_add(1).1); - assert_eq!( - got, want, - "{backend}: s_addk_i32({a}, +1) SCC = {got}, want {want}", - ); - }); - - let addk_neg_cases: &[i32] = &[0, i32::MAX, i32::MIN + 32768, i32::MIN + 32767, i32::MIN]; - let addk_neg_in: Vec<[u32; 4]> = addk_neg_cases - .iter() - .map(|&a| [a as u32, 0, 0, 0]) - .collect(); - run_cases(&addk_neg_min, &addk_neg_in, |backend, i, _, got| { - let a = addk_neg_cases[i]; - let want = u32::from(a.overflowing_add(i32::from(i16::MIN)).1); - assert_eq!( - got, want, - "{backend}: s_addk_i32({a}, -32768) SCC = {got}, want {want}", - ); - }); -} - -#[test] -fn scalar_add_i32_scc_controls_branch() { - run_signed_scc_cases( - "s_add_i32", - &[sop2(0x02, 6, 0, 1)], - &[(i32::MAX, 1), (i32::MIN, -1), (-1, 1), (8, 5)], - i32::overflowing_add, - ); -} - -#[test] -fn scalar_sub_i32_scc_controls_branch() { - run_signed_scc_cases( - "s_sub_i32", - &[sop2(0x03, 6, 0, 1)], - &[(i32::MIN, 1), (i32::MAX, -1), (0, 1), (-8, -3)], - i32::overflowing_sub, - ); -} - -#[test] -fn scalar_addk_i32_scc_controls_branch() { - for imm in [-1i16, 1] { - let addk_s6 = 0xB000_0000 | 0x0F << 23 | 6 << 16 | u32::from(imm as u16); - run_signed_scc_cases( - "s_addk_i32", - &[s_mov_b32(6, 0), addk_s6], - &[(i32::MIN, 0), (i32::MAX, 0), (-1, 0), (8, 0)], - |a, _| a.overflowing_add(i32::from(imm)), - ); - } -} - -#[test] -fn paired_lds_write2_b32() { - check_lds_paired_write("ds_write2_b32", 0x0E, 1, false); -} - -#[test] -fn paired_lds_write2st64_b32() { - check_lds_paired_write("ds_write2st64_b32", 0x0F, 1, true); -} - -#[test] -fn paired_lds_write2_b64() { - check_lds_paired_write("ds_write2_b64", 0x4E, 2, false); -} - -#[test] -fn paired_lds_write2st64_b64() { - check_lds_paired_write("ds_write2st64_b64", 0x4F, 2, true); -} - -const fn vop3p(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16, clamp: bool) -> [u32; 2] { - [ - 0x33 << 26 - | (op as u32 & 0x7F) << 16 - | (clamp as u32) << 15 - | (1 << 14) // opsel_hi[2] = 1 - | vdst as u32, - (0b11 << 27) // opsel_hi[1:0] = 0b11 - | (src0 as u32 & 0x1FF) - | (src1 as u32 & 0x1FF) << 9 - | (src2 as u32 & 0x1FF) << 18, - ] -} - -const fn sopk(op: u8, sdst: u8, simm16: i16) -> u32 { - 0xB000_0000 | (op as u32 & 0x1F) << 23 | (sdst as u32 & 0x7F) << 16 | (simm16 as u16) as u32 -} - -fn run_signed_scc_cases( - name: &str, - body: &[u32], - operands: &[(i32, i32)], - reference: impl Fn(i32, i32) -> (i32, bool), -) { - let mut words = body.to_vec(); - words.extend([ - 0xBF85_0001, // s_cbranch_scc1 over the next instruction - s_mov_b32(2, 0x80), // s2 = 0 when SCC is clear - sop2(0x12, 7, 6, 2), // s_xor_b32 s7, s6, s2 - vop1(0x001, 0, sgpr(7)), // v_mov_b32 v0, s7 - ]); - let shader = build_valu_cs(&words); - // First read the arithmetic result unchanged, then toggle its high bit - // only when SCC is set. This checks both outputs with the single-dword UAV. - let inputs: Vec<_> = operands - .iter() - .flat_map(|&(a, b)| [[a as u32, b as u32, 0, 0], [a as u32, b as u32, 1 << 31, 0]]) - .collect(); - run_cases(&shader, &inputs, |backend, _, [a, b, mask, _], got| { - let (result, overflow) = reference(a as i32, b as i32); - let expected = result as u32 ^ if overflow { mask } else { 0 }; - assert_eq!( - got, expected, - "{backend}: {name}({:#010x}, {:#010x}), SCC mask {mask:#010x}", - a, b, - ); - }); -} - -fn check_lds_paired_write(name: &str, write_op: u32, width: usize, stride64: bool) { - const LANES: u32 = 64; - const DWORDS_PER_LANE: usize = 4; - const WAIT_LDS: u32 = 0xBF8C_C07F; // s_waitcnt lgkmcnt(0) - let inputs = [0x1234_5678, 0x9ABC_DEF0, 0x0BAD_F00D, 0xFEED_BEEF]; - let read_op = if width == 1 { 0x36 } else { 0x76 }; - let scale = 4 * width as u32 * if stride64 { 64 } else { 1 }; - let data1 = 1 + width as u32; - for same_offset in [false, true] { - // Each lane starts at its own aligned 16-byte offset. Use a - // separation of at least 1024 bytes for the st64 accesses. - let distinct_offset = if stride64 { 6 } else { 3 }; - let offsets = [2, if same_offset { 2 } else { distinct_offset }]; - let mut body = Vec::from(vop3(0x11A, 0, 132, vgpr(0), 0)); // v0 = thread id << 4 - body.extend([ - 0x36 << 26 | write_op << 18 | offsets[0] | offsets[1] << 8, - 1 << 8 | data1 << 16, // Address = v0, DATA0 = v1, DATA1 = v2 or v3. - WAIT_LDS, - ]); - for (element, &offset) in offsets.iter().enumerate() { - body.extend([ - 0x36 << 26 | read_op << 18 | (offset * scale), - 5 << 24, - WAIT_LDS, - ]); - let [mut store, operands] = buffer_store_dword(5, 8, 8 * element as u16); - store |= 1 << 12; // offen: v0 is the per-lane byte offset. - if width == 2 { - store |= 1 << 18; // buffer_store_dwordx2 - } - body.extend([store, operands]); - } - let shader = build_test_cs( - &body, - ComputeIo { - rsrc2: (5 << 1) | (8 << 15), // 5 user SGPRs, 4096 bytes of LDS. - threads: [LANES, 1, 1], - }, - &[], - ); - run_output_cases( - &shader, - &[inputs], - LANES * DWORDS_PER_LANE as u32, - |backend, _, _, out| { - let second = if same_offset { 0 } else { width }; - assert_eq!(out.len(), LANES as usize * DWORDS_PER_LANE); - let (lanes, _) = out.as_chunks::(); - for (lane, values) in lanes.iter().enumerate() { - assert_eq!( - &values[..width], - &inputs[..width], - "{backend}: {name}, offsets {offsets:?}, lane {lane}, DATA0" - ); - assert_eq!( - &values[2..2 + width], - &inputs[second..second + width], - "{backend}: {name}, offsets {offsets:?}, lane {lane}, second value" - ); - } - }, - ); - } -} - -fn build_test_cs(body: &[u32], compute: ComputeIo, result_store: &[u32]) -> HostShader { - let mut words = Vec::new(); - // s[4:5] = descriptor table address (heap index 0 -> byte offset 0). - words.push(s_mov_b32(5, 0x80)); // inline constant 0 - words.extend_from_slice(&s_load_dwordx4(8, 4)); - // Copy root constants s0..s3 into v1..v4 so VALU instructions operate on - // VGPRs just as they do in real shaders. - for i in 0..4u8 { - words.push(vop1(0x001, i + 1, sgpr(i))); // v_mov_b32 - } - words.extend_from_slice(body); - words.extend_from_slice(result_store); - words.push(S_ENDPGM); + let mut words = Vec::new(); + words.push(s_mov_b32(5, 0x80)); + words.extend_from_slice(&s_load_dwordx4(8, 4)); + // Per-lane f64 input in v[6:7] = (s0, s1). + words.push(vop1(0x001, 6, sgpr(0))); + words.push(vop1(0x001, 7, sgpr(1))); + // Whole-wave f64 sum over Wave32 with s_mov_b32 copy before EXEC restore. + words.push(s_or_saveexec_b32(12, 0xC1)); + words.extend_from_slice(&vop3(0x101, 2, 0x80, vgpr(6), sgpr(12))); + words.extend_from_slice(&vop3(0x101, 3, 0x80, vgpr(7), sgpr(12))); + for sel in [14570689u32, 9658386, 2340] { + words.extend_from_slice(&v_mov_dpp8(4, 2, sel)); + words.extend_from_slice(&v_mov_dpp8(5, 3, sel)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); // v_add_f64 + } + words.extend_from_slice(&v_mov_row_mirror(4, 2)); + words.extend_from_slice(&v_mov_row_mirror(5, 3)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); + words.extend_from_slice(&vop3(0x378, 4, vgpr(2), 0x80, 0x80)); // v_permlanex16_b32 + words.extend_from_slice(&vop3(0x378, 5, vgpr(3), 0x80, 0x80)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); + words.extend_from_slice(&vop3(0x360, 14, vgpr(2), 0x80, 0)); // v_readlane_b32 s14, v2, 0 + words.extend_from_slice(&vop3(0x360, 15, vgpr(3), 0x80, 0)); // v_readlane_b32 s15, v3, 0 + words.push(s_mov_b32(16, 14)); + words.push(s_mov_b32(17, 15)); + words.push(s_mov_b32(126, 12)); // restore exec_lo + words.push(vop1(0x00f, 0, sgpr(16))); // v_cvt_f32_f64 v0, s[16:17] + words.extend_from_slice(&buffer_store_dword(0, 8, 0)); + words.push(S_ENDPGM); let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { stage: HwStage::Cs, wave64: false, - vgprs: 8, + vgprs: 12, layout: vec![ RootParam { root: RootType::Constants, @@ -2156,7 +1533,10 @@ fn build_test_cs(body: &[u32], compute: ComputeIo, result_store: &[u32]) -> Host user_data: 4, slot: 1, }], - io: StageIo::Cs(compute), + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [4, 1, 1], + }), code, }; @@ -2175,8 +1555,6 @@ fn build_test_cs(body: &[u32], compute: ComputeIo, result_store: &[u32]) -> Host outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - crumbs: None, - emulate_mesh: false, }) .expect("lower"); @@ -2184,44 +1562,36 @@ fn build_test_cs(body: &[u32], compute: ComputeIo, result_store: &[u32]) -> Host stage: HwStage::Cs, dxil: lowered.dxil, user_data: lowered.user_data, - static_samplers: super::build_static_samplers(&lowered.samplers, &lowered.cmp_samplers), samplers: lowered.samplers, + static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, - address_map: lowered.address_map, - descriptor_words: lowered.descriptor_words, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), - mesh_emu: None, }; - if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); - let ours = copy[4..20].to_vec(); v.validate(&mut copy).expect("DXIL validation failed"); - assert_eq!(copy[4..20], ours[..], "container hash mismatch"); } - shader -} - -fn run_output_cases( - shader: &HostShader, - cases: &[[u32; 4]], - output_dwords: u32, - mut check: impl FnMut(&str, usize, [u32; 4], &[u32]), -) { + let cases: &[(f64, f32)] = &[(1.25, 5.0), (-0.75, -3.0)]; let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); - let mut ran = 0; for (label, warp) in [("hardware", false), ("warp", true)] { let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); continue; }; - let (root, pso) = host - .compute_pipeline(shader) - .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); - for (i, &inputs) in cases.iter().enumerate() { + let (root, pso) = match host.compute_pipeline(&shader) { + Ok(p) => p, + // WARP does not support fixed WaveSize(32) on SM 6.6. + Err(e) if warp => { + eprintln!("{label}: compute_pipeline skipped ({e})"); + continue; + } + Err(e) => panic!("{label}: compute_pipeline failed: {e}"), + }; + for &(x, want) in cases { + let b = x.to_bits(); + let inputs = [b as u32, (b >> 32) as u32, 0, 0]; let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; for u in &shader.user_data { ud[u.index as usize] = match (u.root, u.slot) { @@ -2236,197 +1606,19 @@ fn run_output_cases( &pso, &Dispatch { roots: vec![(0, Root::Constants(ud))], - views: &[View::RawUav(output_dwords)], + views: &[View::RawUav(1)], samplers: &[], groups: [1, 1, 1], }, ) .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - check(label, i, inputs, &out[0]); - } - ran += 1; - } - assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); -} -#[test] -fn reachability_overwritten_missing_phis_match_on_host_and_warp() { - // 1. Correlated overwrite of a missing descriptor word (`s13`) across two joins: - // when s0 == 0: load s[12:15], read UAV via raw buffer_load_dword, then overwrite s13 = 29; - // when s0 != 0: set s13 = 17, skip overwrite. Result v0 = s13. - let desc_word_shader = build_valu_cs(&[ - 0x7E0C_0280, // v_mov_b32 v6, 0 - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 - 0xBF85_0002, // s_cbranch_scc1 +2 - 0xBE8D_0391, // s_mov_b32 s13, 17 - 0xBF82_0004, // s_branch +4 - s_load_dwordx4(12, 4)[0], - s_load_dwordx4(12, 4)[1], - 0xE030_0000, - 0x8003_0506, // buffer_load_dword v5, v6, s[12:15], 0 - 0xBF84_0001, // s_cbranch_scc0 +1 (skip overwrite only when s0 != 0) - 0xBE8D_039D, // s_mov_b32 s13, 29 - vop1(0x001, 0, sgpr(13)), - ]); - // 2. Correlated overwrite of an unknown-stride buffer_load_dword (`v5` -> Missing) across two joins: - // when s0 == 0: load with idxen (stride = 0 in build_valu_cs -> unknown stride), then overwrite v5 = 29; - // when s0 != 0: v5 = 17, skip overwrite. Result v0 = v5. - let unknown_stride_shader = build_valu_cs(&[ - 0x7E0C_0280, // v_mov_b32 v6, 0 - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 - 0xBF85_0002, // s_cbranch_scc1 +2 - 0x7E0A_0291, // v_mov_b32 v5, 17 - 0xBF82_0004, // s_branch +4 - s_load_dwordx4(12, 4)[0], - s_load_dwordx4(12, 4)[1], - 0xE030_2000, - 0x8003_0506, // buffer_load_dword v5, v6, s[12:15], 0 idxen (unknown stride) - 0xBF84_0001, // s_cbranch_scc0 +1 (skip overwrite only when s0 != 0) - 0x7E0A_029D, // v_mov_b32 v5, 29 - vop1(0x001, 0, vgpr(5)), - ]); - // 3. Loop-invariant infeasible s_memtime phi (latch uses VCC to preserve SCC): - // when s0 == 0: loop runs s_memtime -> s13, then overwrites s13 = 29 after loop; - // when s0 != 0: loop keeps s13 = 17, skips overwrite after loop. - let loop_shader = build_valu_cs(&[ - 0xBE8D_0391, // s_mov_b32 s13, 17 - 0x7E0E_0280, // v_mov_b32 v7, 0 - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 - 0xBF84_0003, // s_cbranch_scc0 +3 - 0xF490_0180, - 0, // s_memtime s[6:7] - 0xBE8D_0306, // s_mov_b32 s13, s6 - 0x4A0E_0E81, // v_add_nc_u32 v7, 1, v7 - 0x7D88_0E82, // v_cmp_gt_u32 vcc_lo, 2, v7 - 0xBF87_FFF9, // s_cbranch_vccnz -7 - 0xBF84_0001, // s_cbranch_scc0 +1 - 0xBE8D_039D, // s_mov_b32 s13, 29 - vop1(0x001, 0, sgpr(13)), - ]); - - let cases = [([0, 0, 0, 0], 29u32), ([1, 0, 0, 0], 17u32)]; - let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); - for (name, shader) in [ - ("desc_word", &desc_word_shader), - ("unknown_stride", &unknown_stride_shader), - ("loop_memtime", &loop_shader), - ] { - run_cases(shader, &inputs, |backend, i, inp, got| { - let want = cases[i].1; assert_eq!( - got, want, - "{backend} {name} s0={}: got {got}, want {want}", - inp[0] + out[0][0], + want.to_bits(), + "{label}: wave f64 sum({x}) = {:#010x}, want {:#010x}", + out[0][0], + want.to_bits(), ); - }); - } -} -#[test] -fn scalar_buffer_loads_read_a_uav_through_its_table() { - // The UAV is the one `build_valu_cs` stores to: write root constant 0 - // to its dword 0, read it back with a scalar buffer load, and store - // that. - let body = [ - 0xE070_0000, - 0x8002_0100, // buffer_store_dword v1, off, s[8:11], 0 - 0xF420_0304, - 0xFA00_0000, // s_buffer_load_dword s12, s[8:11], null - 0x7E00_020C, // v_mov_b32 v0, s12 - ]; - let shader = build_valu_cs(&body); - let cases = [[0x1234_5678, 0, 0, 0], [0xDEAD_BEEF, 0, 0, 0]]; - run_cases(&shader, &cases, |backend, _, inp, got| { - assert_eq!(got, inp[0], "{backend}: read back {got:#010x}"); - }); -} - -#[test] -fn v_cmp_16bit_ignores_vop3_op_sel() { - // v_cmp_lt_f16_e64 s6, v1, v2 (VOP3 encoding of VOPC 0x0c9), op_sel:[1,0]; - // then v_cndmask_b32_e64 v0, 0, 1, s6. - let [mut hi0, hi1] = vop3(0x0c9, 6, vgpr(1), vgpr(2), 0); - hi0 |= 1 << 11; // op_sel[0] = high half, which RDNA2 ignores here - let f16_hi = build_valu_cs(&[ - hi0, - hi1, - vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], - vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], - ]); - // The same compare with op_sel clear, as a control. - let f16_lo = build_valu_cs(&[ - vop3(0x0c9, 6, vgpr(1), vgpr(2), 0)[0], - vop3(0x0c9, 6, vgpr(1), vgpr(2), 0)[1], - vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], - vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], - ]); - // v_cmp_lt_u16_e64 with op_sel:[1,0] (VOPC 0x0a9). - let [mut hi0, hi1] = vop3(0x0a9, 6, vgpr(1), vgpr(2), 0); - hi0 |= 1 << 11; - let u16_hi = build_valu_cs(&[ - hi0, - hi1, - vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], - vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], - ]); - - // Low halves decide: 1.0 < 1.5 true; 2.0 < 1.5 false. In the second - // case honouring op_sel (high half 1.0) would wrongly say true. - let f16_inputs = [ - [0x4000_3C00, 0x0000_3E00, 0, 0], - [0x3C00_4000, 0x0000_3E00, 0, 0], - ]; - let f16_wants = [1u32, 0u32]; - for (name, shader) in [("op_sel high", &f16_hi), ("op_sel low", &f16_lo)] { - run_cases(shader, &f16_inputs, |backend, i, inp, got| { - let want = f16_wants[i]; - assert_eq!( - got, want, - "{backend}: v_cmp_lt_f16({name}) ({:#010x}, {:#010x}) = {got}, want {want}", - inp[0], inp[1], - ); - }); - } - - // u16: low 9 < 5 is false; honouring op_sel (high half 1) would say true. - let u16_inputs = [[0x0001_0009, 0x0000_0005, 0, 0]]; - let u16_wants = [0u32]; - run_cases(&u16_hi, &u16_inputs, |backend, i, inp, got| { - let want = u16_wants[i]; - assert_eq!( - got, want, - "{backend}: v_cmp_lt_u16(op_sel high) ({:#010x}, {:#010x}) = {got}, want {want}", - inp[0], inp[1], - ); - }); -} -/// A select whose mask is a plain SGPR (here a root constant), so the -/// structure pass does not follow it: this lane takes its own bit of the -/// number. Inline 0 and -1 masks pick src0 and src1 in every lane. -#[test] -fn v_cndmask_on_an_untracked_mask_tests_this_lanes_bit() { - // v_cndmask_b32_e64 v0, v1, v2, (VOP3 0x101); s3 holds the mask. - // The lane bit comes out of waveGetLaneIndex; where every available - // adapter rejects the emitted compute pipeline the cases stay untested - // (upstream CI has no GPU: its drivers reject this shader outright). - let from_sgpr = build_valu_cs(&vop3(0x101, 0, vgpr(1), vgpr(2), sgpr(3))); - let hw = &[("hardware", false), ("warp", true)]; - run_cases_lenient( - &from_sgpr, - &[ - [10, 20, 0, 0], - [10, 20, 0, 1], - [10, 20, 0, 2], - [10, 20, 0, !0], - ], - hw, - |label, i, inp, got| { - let want = if inp[3] & 1 != 0 { inp[1] } else { inp[0] }; - assert_eq!(got, want, "{label} case {i}"); - }, - ); - for (mask, pick) in [(128u16, 0usize), (193, 1)] { - let k = build_valu_cs(&vop3(0x101, 0, vgpr(1), vgpr(2), mask)); - run_cases_lenient(&k, &[[10, 20, 0, 0]], hw, |label, _, inp, got| { - assert_eq!(got, inp[pick], "{label} inline {mask}"); - }); + } } } diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 44b1b2b..18425e0 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -69,8 +69,6 @@ fn build(words: &[u32], buffers: bool) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - crumbs: None, - emulate_mesh: false, }) .expect("lower"); // One access with each lane's own heap index, no wave operation. @@ -84,11 +82,8 @@ fn build(words: &[u32], buffers: bool) -> HostShader { static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, - address_map: lowered.address_map, - descriptor_words: lowered.descriptor_words, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), - mesh_emu: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) @@ -99,15 +94,19 @@ fn build(words: &[u32], buffers: bool) -> HostShader { shader } -/// Runs `shader` with `views` at heap indices 0.. (the UAV last) and -/// `samplers` at sampler-heap indices 0.. on the hardware GPU and on WARP (each -/// skipped without a device) and returns, per one that ran, the UAV's 32 -/// dwords. -fn run_with_samplers( - shader: &HostShader, - views: &[View], - samplers: &[D3D12_SAMPLER_DESC], -) -> Vec<(&'static str, Vec)> { +/// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the +/// hardware GPU and on WARP (each skipped without a device) and returns, +/// per one that ran, the UAV's 32 dwords. +fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { + let samplers = [D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxAnisotropy: 1, + MaxLOD: f32::MAX, + ..Default::default() + }]; let mut out = Vec::new(); // One GPU test at a time, with the VALU tests: in parallel on the // hardware adapter and WARP the test process sometimes died of an @@ -137,7 +136,7 @@ fn run_with_samplers( &Dispatch { roots: vec![(0, Root::Constants(ud))], views, - samplers, + samplers: &samplers, groups: [1, 1, 1], }, ) @@ -147,19 +146,6 @@ fn run_with_samplers( out } -fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { - let samplers = [D3D12_SAMPLER_DESC { - Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, - AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - MaxAnisotropy: 1, - MaxLOD: f32::MAX, - ..Default::default() - }]; - run_with_samplers(shader, views, &samplers) -} - /// The red channel each lane sampled from two 1x1 textures, red 1.0 at /// heap index 0 and 2.0 at 1. fn sampled(shader: &HostShader) -> Vec<(&'static str, Vec)> { @@ -263,101 +249,3 @@ fn lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx() { } } } - -#[test] -fn lanes_sample_texture_after_redundant_partial_write() { - use crate::resource::tests::joined_with_redundant_write; - let shader = build(&joined_with_redundant_write(), false); - let results = sampled(&shader); - assert!(!results.is_empty()); - let want: Vec = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect(); - for (label, red) in results { - assert_eq!(red, want, "{label}"); - } -} - -#[test] -fn lanes_sample_joined_sampler_after_redundant_partial_write() { - use crate::resource::tests::joined_sampler_shader; - let shader = build(&joined_sampler_shader(Some(0x7E08_0218)), false); - let tex = [[1.0f32, 0.0, 0.0, 1.0], [2.0f32, 0.0, 0.0, 1.0]]; - let views = [ - View::Texture(2, 1, &tex), - View::Texture(2, 1, &tex), - View::RawUav(32), - ]; - let sampler = |addr| D3D12_SAMPLER_DESC { - Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, - AddressU: addr, - AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - MaxAnisotropy: 1, - MaxLOD: f32::MAX, - ..Default::default() - }; - let wrap = sampler(D3D12_TEXTURE_ADDRESS_MODE_WRAP); - let clamp = sampler(D3D12_TEXTURE_ADDRESS_MODE_CLAMP); - - for (swapped, samplers) in [(false, [wrap, clamp]), (true, [clamp, wrap])] { - let results = run_with_samplers(&shader, &views, &samplers); - assert!(!results.is_empty()); - let want: Vec = (0..32) - .map(|l| if (l < 16) ^ swapped { 1.0 } else { 2.0 }) - .collect(); - for (label, words) in results { - let red: Vec = words.into_iter().map(f32::from_bits).collect(); - assert_eq!(red, want, "{label}, swapped {swapped}"); - } - } -} - -#[test] -fn lanes_sample_after_vgpr_swap_and_word_extract() { - use crate::resource::tests::WATERFALL_JOINED_WAVE32; - let mut words = WATERFALL_JOINED_WAVE32.to_vec(); - let at = words.iter().position(|&w| w == 0x887E_147E).unwrap() + 1; - words.splice( - at..at, - [ - 0x7E08_CB05, // v_swap_b32 v4, v5 - 0x7E0A_CB04, // v_swap_b32 v5, v4 - 0x3808_0880, // v_or_b32 v4, 0, v4 - 0xD700_0014, - 0x0002_0CA0, // v_lshrrev_b64 v[20:21], 32, v[6:7] - 0x7E0E_0314, // v_mov_b32 v7, v20 - 0xD744_0016, - 0x03FE_1308, - 0x0706_0504, // v_perm_b32 v22, v8, v9, 0x07060504 - 0x7E10_0316, // v_mov_b32 v8, v22 - ], - ); - let shader = build(&words, false); - let results = sampled(&shader); - assert!(!results.is_empty()); - let want: Vec = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect(); - for (label, red) in results { - assert_eq!(red, want, "{label}"); - } -} -#[test] -fn lanes_sample_their_arm_after_a_redundant_masked_write() { - use crate::resource::tests::WATERFALL_JOINED_WAVE32; - let mut words = WATERFALL_JOINED_WAVE32.to_vec(); - let at = words.iter().position(|&w| w == 0x887E_147E).unwrap() + 1; - words.splice( - at..at, - [ - 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 (lane < 16) - 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo - 0x7E08_0218, // v_mov_b32 v4, s24 (same word the then arm wrote) - 0xBEFE_0312, // s_mov_b32 exec_lo, s18 - ], - ); - let shader = build(&words, false); - let results = sampled(&shader); - assert!(!results.is_empty()); - let want: Vec = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect(); - for (label, red) in results { - assert_eq!(red, want, "{label}"); - } -} diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index c9f83c8..1d7a91b 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -80,7 +80,7 @@ impl Op { /// 2k and 2k+1, then two such pairs side by side, and so on up to the two halves of the /// wave. Sums joined only that way form the balanced tree over the lanes in their order, /// whichever of the two a lane adds to the other (the addition is commutative). -pub(super) fn buddies(a: u64, b: u64) -> bool { +fn buddies(a: u64, b: u64) -> bool { let n = a.count_ones(); if n != b.count_ones() || !n.is_power_of_two() || n == 64 { return false; @@ -112,6 +112,15 @@ pub(crate) enum Sym { ident: u32, lanes: u64, }, + /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over + /// `lanes` of `mask ? f64(lo, hi) : 0.0`. + Red64F { + lo: Value, + hi: Value, + mask: Value, + lanes: u64, + high: bool, + }, } /// What a value a section leaves holds in every lane. @@ -123,6 +132,8 @@ pub(crate) enum Shape { Masked(Value, Value, u32), /// `op` over every lane. Active(Op, Value, Value, u32), + /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over every lane. + ActiveF64(Value, Value, Value, bool), /// `op` over the lanes below (`inclusive`: and including) each lane. Prefix(Op, Value, Value, u32, bool), } @@ -298,13 +309,28 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all; continue; } - if let Fields::Sop { src, .. } = &inst.fields { + if let Fields::Sop { dst, src, .. } = &inst.fields { if name.starts_with("s_and_b") && src.iter().any(|o| matches!(*o, Operand::Scalar { code, .. } if inst.read(Reg::S(code)).is_some_and(|v| masked.contains(&v)))) && let Some(&(_, w)) = inst.writes.iter().find(|w| matches!(w.0, Reg::S(_))) { masked.push(w); } + if name == "s_mov_b32" + && let (Some(Operand::Scalar { code: dc, .. }), Some(s0)) = (dst, src.first()) + && *dc != NULL + && let Some(w) = inst.write(Reg::S(*dc)) + { + let sym = match *s0 { + Operand::Scalar { code, .. } if code != NULL => inst + .read(Reg::S(code)) + .map_or(Sym::Unknown, |x| uni.get(&x).copied().unwrap_or(Sym::Uni(x))), + Operand::Const(c) => crate::resource::inline(c).map_or(Sym::Unknown, Sym::K), + Operand::Literal(x) => Sym::K(x), + _ => Sym::Unknown, + }; + uni.insert(w, sym); + } for &(_, w) in &inst.writes { uni.entry(w).or_insert(Sym::Unknown); } @@ -359,6 +385,130 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { } continue; } + if name == "v_add_f64" + && !modifiers + && v.dpp.is_none() + && let Some(Operand::Vector { reg: dreg, .. }) = v.dst + && let (Some(dst_lo), Some(dst_hi)) = + (inst.write(Reg::V(dreg)), inst.write(Reg::V(dreg + 1))) + { + let pair_lanes = |op: Option<&Operand>| -> Option<(Vec, Vec)> { + match *op? { + Operand::Vector { reg, .. } => Some(( + lanes(&Operand::Vector { reg, dwords: 1 }, &vec, &uni), + lanes( + &Operand::Vector { + reg: reg + 1, + dwords: 1, + }, + &vec, + &uni, + ), + )), + Operand::Scalar { code, .. } if code != NULL => Some(( + lanes(&Operand::Scalar { code, dwords: 1 }, &vec, &uni), + lanes( + &Operand::Scalar { + code: code + 1, + dwords: 1, + }, + &vec, + &uni, + ), + )), + _ => None, + } + }; + let old_lo = lanes( + &Operand::Vector { + reg: dreg, + dwords: 1, + }, + &vec, + &uni, + ); + let old_hi = lanes( + &Operand::Vector { + reg: dreg + 1, + dwords: 1, + }, + &vec, + &uni, + ); + let f64_term = |lo_s: Sym, hi_s: Sym| -> Option<(Value, Value, Value, u64)> { + match (lo_s, hi_s) { + ( + Sym::Red { + op: None, + src: lo, + mask: ml, + ident: 0, + lanes: ll, + }, + Sym::Red { + op: None, + src: hi, + mask: mh, + ident: 0, + lanes: lh, + }, + ) if ml == mh && ll == lh => Some((lo, hi, ml, ll)), + ( + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: l1, + high: false, + }, + Sym::Red64F { + lo: lo2, + hi: hi2, + mask: m2, + lanes: l2, + high: true, + }, + ) if (lo1, hi1, m1, l1) == (lo2, hi2, m2, l2) => Some((lo1, hi1, m1, l1)), + _ => None, + } + }; + let mut out_lo = vec![Sym::Unknown; wave as usize]; + let mut out_hi = vec![Sym::Unknown; wave as usize]; + if let (Some((alo, ahi)), Some((blo, bhi))) = + (pair_lanes(v.src.first()), pair_lanes(v.src.get(1))) + { + for l in 0..wave as usize { + let (rl, rh) = match (f64_term(alo[l], ahi[l]), f64_term(blo[l], bhi[l])) { + (Some((lo1, hi1, m1, la)), Some((lo2, hi2, m2, lb))) + if (lo1, hi1, m1) == (lo2, hi2, m2) && la & lb == 0 => + { + ( + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: la | lb, + high: false, + }, + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: la | lb, + high: true, + }, + ) + } + _ => (Sym::Unknown, Sym::Unknown), + }; + out_lo[l] = if exec >> l & 1 != 0 { rl } else { old_lo[l] }; + out_hi[l] = if exec >> l & 1 != 0 { rh } else { old_hi[l] }; + } + } + vec.insert(dst_lo, out_lo); + vec.insert(dst_hi, out_hi); + continue; + } let Some(Operand::Vector { reg: dreg, .. }) = v.dst else { for &(_, w) in &inst.writes { uni.insert(w, Sym::Unknown); @@ -560,6 +710,13 @@ fn shapes( ident, lanes, } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + Sym::Red64F { + lo, + hi, + mask, + lanes, + high, + } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), _ => None, }; for (v, s) in uni { @@ -603,6 +760,13 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { ident, lanes, } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + Sym::Red64F { + lo, + hi, + mask, + lanes, + high, + } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), _ => None, }; } @@ -945,17 +1109,10 @@ mod tests { let p = build(w, true); let insts = &p.blocks[0].insts; let saved = insts[0].write(Reg::S(4)).unwrap(); - let v7 = p - .inputs - .iter() - .find_map(|&(r, v)| (r == Reg::V(7)).then_some(v)) - .unwrap(); + let v7 = p.inputs.iter().find_map(|&(r, v)| (r == Reg::V(7)).then_some(v)).unwrap(); // ..., v_readlane_b32 s7, v1, 0; s_mov_b64 exec, s[4:5]; s_endpgm let total = insts[insts.len() - 3].write(Reg::S(7)).unwrap(); - ( - sections(&p, 0)[&0].shapes.get(&total).copied(), - Shape::Active(Op::AddH, v7, saved, 0), - ) + (sections(&p, 0)[&0].shapes.get(&total).copied(), Shape::Active(Op::AddH, v7, saved, 0)) }; let (found, want) = shape(&words(pairs, quads)); assert_eq!(found, Some(want)); diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index 9162d38..db82f33 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -33,7 +33,7 @@ fn program(skip: u32) -> NativeProgram { 0x7E00_0207, // v_mov_b32 v0, s7 0x38 << 26 | 0x1C << 18, 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 - 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] ]); native(&words) } @@ -94,11 +94,7 @@ fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram { } /// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide. -fn lowered( - native: &NativeProgram, - p: &ir::Program, - wide: &HashSet, -) -> Result { +fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet) -> Result { let st = structure::structure_wide(p, wide).expect("structure"); let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track"); let io = io::raise(p, native).expect("io::raise"); @@ -113,8 +109,6 @@ fn lowered( outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - crumbs: None, - emulate_mesh: false, }); lower::TEST_HOST_WAVE.set(was); let lowered = lowered?; @@ -128,9 +122,6 @@ fn lowered( root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, - mesh_emu: None, - address_map: lowered.address_map, - descriptor_words: lowered.descriptor_words, }) } @@ -147,13 +138,7 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 ]; // (the wave OR's words with v_add_f16 for v_or_b32: opcode 50 for 28) - words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| { - if w >> 25 == 28 { - w & 0x01FF_FFFF | 50 << 25 - } else { - w - } - })); + words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w })); words.extend_from_slice(&[ 0x7E00_0207, // v_mov_b32 v0, s7 0x38 << 26 | 0x1C << 18, @@ -161,14 +146,7 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { ]); let native = native(&words); let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - assert_eq!( - p.blocks - .iter() - .flat_map(|b| &b.insts) - .filter(|i| i.name() == "v_add_f16") - .count(), - 6 - ); + assert_eq!(p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "v_add_f16").count(), 6); let shader = lowered(&native, &p, &HashSet::new()).expect("lower"); if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -176,8 +154,7 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { } // the console's sum: lanes 2k and 2k+1, then pairs, ... each addition rounded to 16 bits // (to nearest, ties to even); values here are normal numbers - let wide = - |h: u16| f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13); + let wide = |h: u16| f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13); let narrow = |f: f32| { let b = f.to_bits(); let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF); @@ -191,13 +168,8 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect(); } let in_a_row = terms.iter().copied().reduce(add).unwrap(); - assert_ne!( - tree[0], in_a_row, - "these terms tell the tree from another order" - ); - let _one = super::valu_tests::ONE_AT_A_TIME - .lock() - .unwrap_or_else(|e| e.into_inner()); + assert_ne!(tree[0], in_a_row, "these terms tell the tree from another order"); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let Ok(host) = Host::new(false) else { eprintln!("no SM 6.6 hardware device; not run"); return; @@ -205,9 +177,7 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { let (root, pso) = match host.compute_pipeline(&shader) { Ok(x) => x, Err(e) => { - eprintln!( - "the hardware device does not take this program (waves of 32?): {e}; not run" - ); + eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run"); return; } }; @@ -225,16 +195,8 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { ) .unwrap_or_else(|e| panic!("dispatch failed: {e}")); // (the high half is lane 0's term's: zero) - assert_eq!( - out[0][0], - u32::from(tree[0]), - "tree {:#x}, in a row {in_a_row:#x}", - tree[0] - ); - eprintln!( - "ran on the hardware device: the sum {:#x} of the console's tree", - tree[0] - ); + assert_eq!(out[0][0], u32::from(tree[0]), "tree {:#x}, in a row {in_a_row:#x}", tree[0]); + eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]); } /// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 @@ -254,23 +216,14 @@ fn a_16_bit_sum_rounds_to_nearest_when_asked_to() { ]; let native = native(&words); let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - assert!( - p.blocks - .iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "v_add_f16") - ); - let _one = super::valu_tests::ONE_AT_A_TIME - .lock() - .unwrap_or_else(|e| e.into_inner()); + assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "v_add_f16")); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); for nearest in [false, true] { let was = lower::TEST_F16_NEAREST.replace(Some(nearest)); let shader = lowered(&native, &p, &HashSet::new()); lower::TEST_F16_NEAREST.set(was); let shader = shader.expect("lower"); - if let Ok(mut v) = - validator::Validator::load(validator::Validator::default_path().as_deref()) - { + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); v.validate(&mut copy).expect("DXIL validation failed"); } @@ -307,10 +260,7 @@ fn a_16_bit_sum_rounds_to_nearest_when_asked_to() { #[test] fn a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide() { - for (skip, name) in [ - (0xBF88_0000, "s_cbranch_execz"), - (0xBF84_0000, "s_cbranch_scc0"), - ] { + for (skip, name) in [(0xBF88_0000, "s_cbranch_execz"), (0xBF84_0000, "s_cbranch_scc0")] { a_wave_or_inside(skip, name); } } @@ -350,9 +300,7 @@ fn a_wave_or_inside(skip: u32, name: &str) { } // On a GPU that takes waves of 32 (two host waves for the console's one): the OR is of // both halves, whichever half's lanes take the branch. - let _one = super::valu_tests::ONE_AT_A_TIME - .lock() - .unwrap_or_else(|e| e.into_inner()); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let Ok(host) = Host::new(false) else { eprintln!("no SM 6.6 hardware device; not run"); return; @@ -360,20 +308,12 @@ fn a_wave_or_inside(skip: u32, name: &str) { let (root, pso) = match host.compute_pipeline(&shader) { Ok(x) => x, Err(e) => { - eprintln!( - "the hardware device does not take this program (waves of 32?): {e}; not run" - ); + eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run"); return; } }; // (threads below s0 take the branch; thread t gives bit t >> 1) - for (below, expected) in [ - (64u32, u32::MAX), - (40, 0x000F_FFFF), - (33, 0x0001_FFFF), - (10, 0x1F), - (1, 1), - ] { + for (below, expected) in [(64u32, u32::MAX), (40, 0x000F_FFFF), (33, 0x0001_FFFF), (10, 0x1F), (1, 1)] { let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; for u in &shader.user_data { if let (RootType::Constants, 0, 0) = (u.root, u.slot, u.dword) { @@ -453,18 +393,9 @@ fn a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is() { let mut copy = shader.dxil.clone(); v.validate(&mut copy).expect("DXIL validation failed"); } - let _one = super::valu_tests::ONE_AT_A_TIME - .lock() - .unwrap_or_else(|e| e.into_inner()); - for (below, other, expected) in [ - (32u32, 0u32, u32::MAX), - (10, 0, 0x3FF), - (0, 0, 0), - (10, 1, 5), - ] { - let Some(got) = on_the_card(&shader, [below, other]) else { - return; - }; + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for (below, other, expected) in [(32u32, 0u32, u32::MAX), (10, 0, 0x3FF), (0, 0, 0), (10, 1, 5)] { + let Some(got) = on_the_card(&shader, [below, other]) else { return }; assert_eq!(got, expected, "{below} lanes in the mask, s1 = {other}"); } eprintln!("ran on the hardware device: the mask's bits, or the number"); @@ -495,12 +426,7 @@ fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() let native = native_of(&words, false, 32); let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); let branch = (0..p.blocks.len()) - .find(|&b| { - p.blocks[b] - .insts - .last() - .is_some_and(|i| i.name() == "s_cbranch_execz") - }) + .find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz")) .expect("the skip"); lower::take_needs(); let per_lane = lowered(&native, &p, &HashSet::new()); @@ -510,32 +436,17 @@ fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() per_lane.err() ); let st = structure::structure(&p).expect("structure"); - assert_eq!( - lower::branches_around(&st, &lower::take_needs()), - Some(vec![branch]) - ); + assert_eq!(lower::branches_around(&st, &lower::take_needs()), Some(vec![branch])); let shader = lowered(&native, &p, &HashSet::from([branch])).expect("lower"); if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); v.validate(&mut copy).expect("DXIL validation failed"); } - let _one = super::valu_tests::ONE_AT_A_TIME - .lock() - .unwrap_or_else(|e| e.into_inner()); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); // (lanes below s0 inside, s1) -> what lane 31 stores: 2 if SCC was set at the branch - for (below, s1, expected) in [ - (0u32, 7u32, 1u32), - (10, 7, 2), - (10, 3, 1), - (32, 3, 1), - (32, 7, 2), - ] { - let Some(got) = on_the_card(&shader, [below, s1]) else { - return; - }; + for (below, s1, expected) in [(0u32, 7u32, 1u32), (10, 7, 2), (10, 3, 1), (32, 3, 1), (32, 7, 2)] { + let Some(got) = on_the_card(&shader, [below, s1]) else { return }; assert_eq!(got, expected, "{below} lanes inside, s1 = {s1}"); } - eprintln!( - "ran on the hardware device: the inner test's SCC for every lane once some lane is inside" - ); + eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside"); } diff --git a/crates/victory-shader/src/gfx10/fields.rs b/crates/victory-shader/src/gfx10/fields.rs index 524e33d..2773b3c 100644 --- a/crates/victory-shader/src/gfx10/fields.rs +++ b/crates/victory-shader/src/gfx10/fields.rs @@ -11,7 +11,9 @@ use super::{Encoding, Instruction}; pub enum Operand { /// Scalar registers by operand code: 0-105 `s0`-`s105`, 106/107 /// `vcc_lo`/`vcc_hi`, 108-123 `ttmp0`-`ttmp15`, 124 `m0`, 125 `null`, - /// 126/127 `exec_lo`/`exec_hi`. + /// 126/127 `exec_lo`/`exec_hi`. The decoder gives no code above 127; the + /// IR names scalars parked in VGPR lanes by the codes from 128 up + /// (`crate::ir::PARKED`). Scalar { code: u8, dwords: u8, @@ -233,32 +235,19 @@ impl Instruction { } Encoding::Sopp => Fields::Sopp { imm: w0 as u16 }, Encoding::Smem => { - let sdata = (w0 >> 6 & 0x7F) as u8; - // s_atc_probe*: SDATA is a 7-bit immediate, not an SGPR. The - // buffer form's resource is 4 dwords. GLC and DLC are not operands. - let probe = matches!(name, "s_atc_probe" | "s_atc_probe_buffer"); - let data = if probe { - Some(Operand::Literal(u32::from(sdata))) - } else { - match name { - "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => None, - n if n.starts_with("s_dcache_discard") => None, - "s_memtime" | "s_memrealtime" => Some(scalar(sdata, 2)), - _ => Some(scalar(sdata, data_dwords(name))), - } + let data = match name { + "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => None, + n if n.starts_with("s_dcache_discard") => None, + "s_memtime" | "s_memrealtime" => Some(2), + _ => Some(data_dwords(name)), }; - let base = - 2 + 2 * u8::from(name.starts_with("s_buffer_") || name == "s_atc_probe_buffer"); + let base = 2 + 2 * u8::from(name.starts_with("s_buffer_")); Fields::Smem { - data, + data: data.map(|d| scalar((w0 >> 6 & 0x7F) as u8, d)), base: scalar(((w0 & 0x3F) << 1) as u8, base), offset: (w1 << 11) as i32 >> 11, soffset: scalar((w1 >> 25) as u8, 1), - cache: if probe { - Cache::default() - } else { - cache(bit(w0, 16), false, bit(w0, 14)) - }, + cache: cache(bit(w0, 16), false, bit(w0, 14)), } } Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc | Encoding::Vop3 | Encoding::Vop3p => { @@ -781,9 +770,7 @@ fn data_dwords(name: &str) -> u8 { } /// Address dwords of an image opcode: offset, bias, compare, derivatives, -/// coordinates, then LOD/clamp/mip. `a16` packs two coordinate components per -/// dword; the `_g16` form packs the gradients instead, and `a16` alone leaves -/// them at one dword each (RDNA2 supports both, so they are independent). +/// coordinates, then LOD/clamp/mip, packed in pairs with `a16`. fn image_addr_dwords(name: &str, dim: u8, a16: bool) -> u8 { // (coordinates, derivatives per direction) for 1D 2D 3D CUBE 1D_ARRAY // 2D_ARRAY 2D_MSAA 2D_MSAA_ARRAY. @@ -820,1154 +807,9 @@ fn image_addr_dwords(name: &str, dim: u8, a16: bool) -> u8 { } else if name.contains("_mip") { packed += 1; } - // Two gradients per direction, and the packed forms round each direction's - // pair up to a whole dword. - let gradients = if name.contains("_g16") { - 2 * derivs.div_ceil(2) + if a16 { + whole + 2 * derivs.div_ceil(2) + packed.div_ceil(2) } else { - 2 * derivs - }; - let coordinates = if a16 { packed.div_ceil(2) } else { packed }; - whole + gradients + coordinates -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::gfx10::opcodes; - - fn table(encoding: Encoding) -> &'static [(u16, &'static str)] { - match encoding { - Encoding::Sop2 => opcodes::SOP2, - Encoding::Sopk => opcodes::SOPK, - Encoding::Sop1 => opcodes::SOP1, - Encoding::Sopc => opcodes::SOPC, - Encoding::Sopp => opcodes::SOPP, - Encoding::Smem => opcodes::SMEM, - Encoding::Vop2 => opcodes::VOP2, - Encoding::Vop1 => opcodes::VOP1, - Encoding::Vopc => opcodes::VOPC, - Encoding::Vop3 => opcodes::VOP3, - Encoding::Vop3p => opcodes::VOP3P, - Encoding::Vintrp => opcodes::VINTRP, - Encoding::Ds => opcodes::DS, - Encoding::Mubuf => opcodes::MUBUF, - Encoding::Mtbuf => opcodes::MTBUF, - Encoding::Mimg => opcodes::MIMG, - Encoding::Flat => opcodes::FLAT, - Encoding::Global => opcodes::GLOBAL, - Encoding::Scratch => opcodes::SCRATCH, - Encoding::Exp => &[], - } - } - - fn opcode(encoding: Encoding, name: &str) -> u16 { - table(encoding) - .iter() - .find(|(_, n)| *n == name) - .unwrap_or_else(|| panic!("{name} is not {encoding:?}")) - .0 - } - - fn inst_raw(encoding: Encoding, opcode: u16, words: &[u32]) -> Instruction { - Instruction { - offset: 0, - encoding, - opcode, - words: words.to_vec(), - } - } - - fn inst(encoding: Encoding, name: &str, words: &[u32]) -> Instruction { - inst_raw(encoding, opcode(encoding, name), words) - } - - /// VOP1/VOP2/VOPC dw0: source 0, then the opcode (VOP1) or src1 (VOP2) and - /// the destination. - fn vop(vdst: u32, field: u32, src0: u32) -> u32 { - src0 | field << 9 | vdst << 17 - } - - /// VOP3/VOP3P dw0: destination, then abs/neg_hi, opsel, clamp and opcode. - fn dw0(opcode: u16, vdst: u32, hi: u32, sel: u32, clamp: bool) -> u32 { - vdst | hi << 8 | sel << 11 | u32::from(clamp) << 15 | u32::from(opcode) << 16 - } - - /// VOP3/VOP3P dw1: three 9-bit sources, then omod/opsel_hi and neg. - fn dw1(src: [u32; 3], hi: u32, neg: u32) -> u32 { - src[0] | src[1] << 9 | src[2] << 18 | hi << 27 | neg << 29 - } - - fn sgpr(code: u8, dwords: u8) -> Operand { - Operand::Scalar { code, dwords } - } - - fn vgpr(reg: u8, dwords: u8) -> Operand { - Operand::Vector { reg, dwords } - } - - fn valu_raw(encoding: Encoding, opcode: u16, words: &[u32], wave64: bool) -> Valu { - let Fields::Valu(v) = inst_raw(encoding, opcode, words).fields(wave64) else { - panic!("not a VALU instruction"); - }; - v - } - - fn valu(encoding: Encoding, name: &str, words: &[u32], wave64: bool) -> Valu { - valu_raw(encoding, opcode(encoding, name), words, wave64) - } - - #[test] - fn source_codes() { - assert_eq!(source(0, 1, 0), sgpr(0, 1)); - assert_eq!(source(127, 4, 0), sgpr(127, 4)); - // Inline integers 0-64, then -1 to -16. - assert_eq!(source(128, 1, 0), Operand::Const(128)); - assert_eq!(source(192, 1, 0), Operand::Const(192)); - assert_eq!(source(193, 1, 0), Operand::Const(193)); - assert_eq!(source(208, 1, 0), Operand::Const(208)); - // Floats and the read-only special sources. - assert_eq!(source(240, 1, 0), Operand::Const(240)); - assert_eq!(source(254, 1, 0), Operand::Const(254)); - // 255 takes the literal that follows; 256 and up are VGPRs. - assert_eq!(source(255, 2, 0xDEAD_BEEF), Operand::Literal(0xDEAD_BEEF)); - assert_eq!(source(256, 1, 0), vgpr(0, 1)); - assert_eq!(source(511, 2, 0), vgpr(255, 2)); - } - - #[test] - fn scalar_alu_widths() { - assert_eq!(salu_dwords("s_mov_b32"), (1, 1, 1)); - assert_eq!(salu_dwords("s_mov_b64"), (2, 2, 2)); - assert_eq!(salu_dwords("s_and_b64"), (2, 2, 2)); - assert_eq!(salu_dwords("s_lshl_b64"), (2, 2, 1)); - assert_eq!(salu_dwords("s_bfm_b64"), (2, 1, 1)); - assert_eq!(salu_dwords("s_bitreplicate_b64_b32"), (2, 1, 1)); - assert_eq!(salu_dwords("s_bcnt0_i32_b64"), (1, 2, 2)); - assert_eq!(salu_dwords("s_flbit_i32_i64"), (1, 2, 2)); - assert_eq!(salu_dwords("s_cmp_eq_u64"), (2, 2, 2)); - assert_eq!(salu_dwords("s_sext_i32_i8"), (1, 1, 1)); - } - - #[test] - fn vector_alu_widths() { - assert_eq!(valu_dwords("v_add_f32"), (1, [1, 1, 1])); - assert_eq!(valu_dwords("v_add_f64"), (2, [2, 2, 2])); - assert_eq!(valu_dwords("v_lshlrev_b64"), (2, [1, 2, 2])); - assert_eq!(valu_dwords("v_ldexp_f64"), (2, [2, 1, 2])); - assert_eq!(valu_dwords("v_mad_u64_u32"), (2, [1, 1, 2])); - assert_eq!(valu_dwords("v_mqsad_u32_u8"), (4, [2, 1, 4])); - assert_eq!(valu_dwords("v_frexp_exp_i32_f64"), (1, [2, 2, 2])); - assert_eq!(valu_dwords("v_cvt_f32_f16"), (1, [1, 1, 1])); - assert_eq!(valu_dwords("v_cvt_f64_f32"), (2, [1, 1, 1])); - assert_eq!(valu_dwords("v_cvt_f32_f64"), (1, [2, 2, 2])); - assert_eq!(valu_dwords("v_cvt_pkrtz_f16_f32"), (1, [1, 1, 1])); - } - - #[test] - fn data_widths() { - assert_eq!(data_dwords("buffer_load_ubyte"), 1); - assert_eq!(data_dwords("buffer_load_dword"), 1); - assert_eq!(data_dwords("buffer_load_dwordx2"), 2); - assert_eq!(data_dwords("flat_load_dwordx3"), 3); - assert_eq!(data_dwords("flat_load_dwordx4"), 4); - assert_eq!(data_dwords("global_load_sbyte"), 1); - assert_eq!(data_dwords("global_load_b64"), 2); - assert_eq!(data_dwords("global_load_b96"), 3); - assert_eq!(data_dwords("global_load_b128"), 4); - assert_eq!(data_dwords("ds_write_b128"), 4); - // A compare-and-swap moves both the comparison and the replacement. - assert_eq!(data_dwords("buffer_atomic_cmpswap_x2"), 4); - assert_eq!(data_dwords("s_atomic_cmpswap_x2"), 4); - // Packed 16-bit textels halve the data. - assert_eq!(data_dwords("tbuffer_load_format_xy"), 2); - assert_eq!(data_dwords("tbuffer_load_format_d16_xyzw"), 2); - } - - #[test] - fn lds_pairs() { - assert!(ds_pair("ds_read2_b32")); - assert!(ds_pair("ds_write2_b64")); - assert!(ds_pair("ds_wrxchg2st64_rtn_b32")); - assert!(!ds_pair("ds_read_b64")); - assert!(!ds_pair("ds_write_b128")); - } - - #[test] - fn image_address_dwords() { - // (coordinates, derivatives per direction) for each dimension: - // 1D 2D 3D CUBE 1D_ARRAY 2D_ARRAY 2D_MSAA 2D_MSAA_ARRAY. - let cases: &[(&str, u8, bool, u8)] = &[ - ("image_sample", 1, false, 2), - ("image_sample", 1, true, 1), - ("image_sample", 0, true, 1), - ("image_sample", 2, true, 2), - // LOD, bias, compare and offsets are whole dwords; a16 leaves them - // alone and packs only the coordinates. - ("image_sample_l", 1, false, 3), - ("image_sample_l", 1, true, 2), - ("image_sample_l", 2, true, 2), - ("image_sample_b", 1, false, 3), - ("image_sample_b", 1, true, 2), - ("image_sample_c", 1, true, 2), - ("image_sample_c_l", 3, true, 3), - ("image_sample_o", 2, true, 3), - ("image_sample_lz", 1, false, 2), - ("image_gather4", 3, false, 3), - ("image_gather4", 3, true, 2), - ("image_gather4_l", 1, true, 2), - ("image_get_lod", 1, true, 1), - // Explicit derivatives: 2 * components, packed only by g16. - ("image_sample_d", 0, false, 3), - ("image_sample_d", 1, false, 6), - ("image_sample_d", 1, true, 5), - ("image_sample_d", 2, false, 9), - ("image_sample_d_g16", 1, false, 4), - ("image_sample_d_g16", 1, true, 3), - ("image_sample_d_g16", 2, false, 7), - ("image_sample_d_g16", 2, true, 6), - ("image_sample_c_d", 1, true, 6), - ("image_sample_c_d_g16", 1, false, 5), - ("image_sample_c_d_cl", 3, true, 7), - // Coarse derivatives and their compare form. - ("image_sample_cd", 1, true, 5), - ("image_sample_c_cd", 1, true, 6), - ("image_sample_cd_cl", 1, false, 7), - ("image_sample_cd_cl", 1, true, 6), - // Loads, stores, multi-sample and mip chains. - ("image_load", 1, false, 2), - ("image_load", 1, true, 1), - ("image_load_mip", 1, true, 2), - ("image_store_mip", 0, false, 2), - ("image_store_mip", 0, true, 1), - ("image_msaa_load", 6, false, 3), - ("image_msaa_load", 6, true, 2), - ("image_msaa_load", 7, true, 2), - ("image_atomic_add", 1, true, 1), - ("image_get_resinfo", 1, false, 1), - ("image_get_resinfo", 1, true, 1), - ("image_bvh_intersect_ray", 0, false, 11), - ("image_bvh_intersect_ray", 0, true, 8), - ("image_bvh64_intersect_ray", 0, false, 12), - ("image_bvh64_intersect_ray", 0, true, 9), - ]; - for &(name, dim, a16, expected) in cases { - assert_eq!( - image_addr_dwords(name, dim, a16), - expected, - "{name} dim {dim} a16 {a16}" - ); - } - } - - #[test] - fn scalar_instructions() { - // s_and_b64 s[2:3], exec, s[4:5] - let Fields::Sop { dst, src, imm } = - inst(Encoding::Sop2, "s_and_b64", &[(2 << 16) | (4 << 8) | 126]).fields(false) - else { - panic!("not SOP"); - }; - assert_eq!(dst, Some(sgpr(2, 2))); - assert_eq!(src, [sgpr(126, 2), sgpr(4, 2)]); - assert_eq!(imm, None); - - // s_add_u32 s0, s1, literal - let Fields::Sop { dst, src, .. } = - inst(Encoding::Sop2, "s_add_u32", &[255 << 8 | 1, 0xDEAD_BEEF]).fields(false) - else { - panic!("not SOP"); - }; - assert_eq!(dst, Some(sgpr(0, 1))); - assert_eq!(src, [sgpr(1, 1), Operand::Literal(0xDEAD_BEEF)]); - - // s_getpc_b64 writes the pair; s_setpc_b64 only reads one. - let Fields::Sop { dst, src, .. } = - inst(Encoding::Sop1, "s_getpc_b64", &[4 << 16]).fields(false) - else { - panic!("not SOP"); - }; - assert_eq!(dst, Some(sgpr(4, 2))); - assert!(src.is_empty()); - let Fields::Sop { dst, src, .. } = inst(Encoding::Sop1, "s_setpc_b64", &[4]).fields(false) - else { - panic!("not SOP"); - }; - assert_eq!(dst, None); - assert_eq!(src, [sgpr(4, 2)]); - - let Fields::Sop { dst, src, .. } = - inst(Encoding::Sopc, "s_cmp_eq_u64", &[3 << 8]).fields(false) - else { - panic!("not SOP"); - }; - assert!(dst.is_none()); - assert_eq!(src, [sgpr(0, 2), sgpr(3, 2)]); - - // SOPK: the destination field becomes a source for compares. - let Fields::Sop { dst, src, imm } = - inst(Encoding::Sopk, "s_cmpk_lg_u32", &[(5 << 16) | 0x1234]).fields(false) - else { - panic!("not SOP"); - }; - assert_eq!(dst, None); - assert_eq!(src, [sgpr(5, 1)]); - assert_eq!(imm, Some(0x1234)); - - let Fields::Sop { dst, imm, .. } = - inst(Encoding::Sopk, "s_call_b64", &[(8 << 16) | 4]).fields(false) - else { - panic!("not SOP"); - }; - assert_eq!(dst, Some(sgpr(8, 2))); - assert_eq!(imm, Some(4)); - - let Fields::Sop { dst, src, imm } = - inst(Encoding::Sopk, "s_setreg_imm32_b32", &[0x10, 1]).fields(false) - else { - panic!("not SOP"); - }; - assert_eq!(dst, None); - assert_eq!(src, [Operand::Literal(1)]); - assert_eq!(imm, Some(0x10)); - - let Fields::Sop { dst, .. } = - inst(Encoding::Sopk, "s_movk_i32", &[(6 << 16) | 0xFFFF]).fields(false) - else { - panic!("not SOP"); - }; - assert_eq!(dst, Some(sgpr(6, 1))); - - let op = u32::from(opcode(Encoding::Sopp, "s_waitcnt")); - let Fields::Sopp { imm } = - inst(Encoding::Sopp, "s_waitcnt", &[(op << 16) | 0xFC7F]).fields(false) - else { - panic!("not SOPP"); - }; - assert_eq!(imm, 0xFC7F); - } - - #[test] - fn scalar_memory() { - // s_load_dwordx2 s[4:5], s[8:9], s3 offset:-8 glc dlc - let w0 = 4 | (4 << 6) | (1 << 14) | (1 << 16); - let w1 = 0x1F_FFF8 | (3 << 25); - let Fields::Smem { - data, - base, - offset, - soffset, - cache, - } = inst(Encoding::Smem, "s_load_dwordx2", &[w0, w1]).fields(false) - else { - panic!("not SMEM"); - }; - assert_eq!(data, Some(sgpr(4, 2))); - assert_eq!(base, sgpr(8, 2)); - assert_eq!(offset, -8); - assert_eq!(soffset, sgpr(3, 1)); - assert_eq!( - cache, - Cache { - glc: true, - slc: false, - dlc: true - } - ); - - // The offset is 21 bits, signed. - let Fields::Smem { offset, .. } = - inst(Encoding::Smem, "s_load_dword", &[0, 0x0F_FFFF]).fields(false) - else { - panic!("not SMEM"); - }; - assert_eq!(offset, 1_048_575); - let Fields::Smem { offset, .. } = - inst(Encoding::Smem, "s_load_dword", &[0, 0x100_000]).fields(false) - else { - panic!("not SMEM"); - }; - assert_eq!(offset, -1_048_576); - - // Buffer descriptors are four SGPRs; memtime returns a pair. - let Fields::Smem { data, base, .. } = - inst(Encoding::Smem, "s_buffer_load_dwordx4", &[1 | (20 << 6), 0]).fields(false) - else { - panic!("not SMEM"); - }; - assert_eq!(data, Some(sgpr(20, 4))); - assert_eq!(base, sgpr(2, 4)); - let Fields::Smem { data, .. } = - inst(Encoding::Smem, "s_memtime", &[12 << 6, 0]).fields(false) - else { - panic!("not SMEM"); - }; - assert_eq!(data, Some(sgpr(12, 2))); - let Fields::Smem { data, .. } = inst(Encoding::Smem, "s_dcache_inv", &[0, 0]).fields(false) - else { - panic!("not SMEM"); - }; - assert_eq!(data, None); - } - - #[test] - fn vop1_sources_and_destinations() { - let v = valu(Encoding::Vop1, "v_mov_b32", &[vop(3, 0, 256 + 5)], false); - assert_eq!(v.dst, Some(vgpr(3, 1))); - assert_eq!(v.src, [vgpr(5, 1)]); - - let v = valu( - Encoding::Vop1, - "v_readfirstlane_b32", - &[vop(5, 0, 256 + 2)], - false, - ); - assert_eq!(v.dst, Some(sgpr(5, 1))); - assert_eq!(v.src, [vgpr(2, 1)]); - - // No operands: the console compiler keeps a shader hash in the fields. - let v = valu(Encoding::Vop1, "v_nop", &[0xFFFF_FFFF, 0xFFFF_FFFF], false); - assert_eq!(v, Valu::default()); - } - - #[test] - fn sdwa_fields() { - // dst_sel 3, dst_unused 1, clamp, omod 2, src0_sel 1, sext 3, neg 1, - // abs 2, src1_sel 4; src0 is an SGPR (S0), src1 a VGPR. - let ext = 0x2C99_AB08; - let v = valu(Encoding::Vop2, "v_add_f32", &[vop(1, 5, 0xF9), ext], false); - assert_eq!(v.dst, Some(vgpr(1, 1))); - assert_eq!(v.src, [sgpr(8, 1), vgpr(5, 1)]); - let sdwa = v.sdwa.expect("SDWA"); - assert_eq!((sdwa.dst_sel, sdwa.dst_unused), (3, 1)); - assert_eq!(sdwa.src_sel, [1, 4]); - assert_eq!(sdwa.sext, 3); - assert_eq!((v.neg, v.abs), (1, 2)); - assert!(v.clamp); - assert_eq!(v.omod, 2); - - // Bit 31 makes src1 an SGPR: the 8-bit field is the register. - let v = valu( - Encoding::Vop2, - "v_add_f32", - &[vop(1, 6, 0xF9), (1 << 31) | 5], - false, - ); - assert_eq!(v.src, [vgpr(5, 1), sgpr(6, 1)]); - } - - #[test] - fn dpp_permutations() { - let ext = 4 - | (0x101 << 8) - | (1 << 18) - | (1 << 19) - | (1 << 20) - | (1 << 21) - | (1 << 22) - | (1 << 23) - | (0xA << 24) - | (5 << 28); - let v = valu(Encoding::Vop2, "v_add_f32", &[vop(2, 6, 0xFA), ext], false); - assert_eq!(v.src, [vgpr(4, 1), vgpr(6, 1)]); - assert_eq!((v.neg, v.abs), (3, 3)); - assert_eq!( - v.dpp, - Some(Dpp::Row { - ctrl: 0x101, - row_mask: 5, - bank_mask: 0xA, - bound_ctrl: true, - fi: true, - }) - ); - - let ext = 4 | (0x12_3456 << 8); - let v = valu(Encoding::Vop2, "v_add_f32", &[vop(2, 6, 0xE9), ext], false); - assert_eq!( - v.dpp, - Some(Dpp::Lanes { - sel: 0x12_3456, - fi: false - }) - ); - let v = valu(Encoding::Vop2, "v_add_f32", &[vop(2, 6, 0xEA), ext], false); - assert_eq!( - v.dpp, - Some(Dpp::Lanes { - sel: 0x12_3456, - fi: true - }) - ); - } - - #[test] - fn vop2_implicit_operands() { - let v = valu(Encoding::Vop2, "v_cndmask_b32", &[vop(1, 2, 0)], false); - assert_eq!(v.src, [sgpr(0, 1), vgpr(2, 1), sgpr(106, 1)]); - assert_eq!(v.carry, None); - let v = valu(Encoding::Vop2, "v_cndmask_b32", &[vop(1, 2, 0)], true); - assert_eq!(v.src[2], sgpr(106, 2)); - - let v = valu( - Encoding::Vop2, - "v_add_co_ci_u32", - &[vop(3, 4, 256 + 1)], - true, - ); - assert_eq!(v.src, [vgpr(1, 1), vgpr(4, 1), sgpr(106, 2)]); - assert_eq!(v.carry, Some(sgpr(106, 2))); - - // v_madmk takes the literal second, v_madak third. - let v = valu( - Encoding::Vop2, - "v_madmk_f32", - &[vop(1, 3, 256 + 2), 0x3F00_0000], - false, - ); - assert_eq!( - v.src, - [vgpr(2, 1), Operand::Literal(0x3F00_0000), vgpr(3, 1)] - ); - let v = valu( - Encoding::Vop2, - "v_madak_f32", - &[vop(1, 3, 256 + 2), 0x3F00_0000], - false, - ); - assert_eq!( - v.src, - [vgpr(2, 1), vgpr(3, 1), Operand::Literal(0x3F00_0000)] - ); - } - - #[test] - fn compares_write_lane_masks() { - let words = [vop(0, 3, 240)]; - let v = valu(Encoding::Vopc, "v_cmp_gt_f32", &words, false); - assert_eq!(v.dst, Some(sgpr(106, 1))); - assert_eq!(v.src, [Operand::Const(240), vgpr(3, 1)]); - let v = valu(Encoding::Vopc, "v_cmp_gt_f32", &words, true); - assert_eq!(v.dst, Some(sgpr(106, 2))); - let v = valu(Encoding::Vopc, "v_cmpx_gt_f32", &words, false); - assert_eq!(v.dst, Some(sgpr(126, 1))); - } - - #[test] - fn vop3_modifiers() { - let op = opcode(Encoding::Vop3, "v_add_f64"); - let v = valu( - Encoding::Vop3, - "v_add_f64", - &[dw0(op, 2, 2, 0xA, true), dw1([0x101, 0x102, 0], 1, 3)], - false, - ); - assert_eq!(v.dst, Some(vgpr(2, 2))); - assert_eq!(v.src, [vgpr(1, 2), vgpr(2, 2)]); - assert_eq!((v.neg, v.abs, v.opsel), (3, 2, 0xA)); - assert!(v.clamp); - assert_eq!(v.omod, 1); - - // A VOP3-encoded compare writes an SGPR. - let op = opcode(Encoding::Vopc, "v_cmp_gt_f32"); - let v = valu_raw( - Encoding::Vop3, - op, - &[dw0(op, 6, 0, 0, false), dw1([0x101, 0x102, 0], 0, 0)], - true, - ); - assert_eq!(v.dst, Some(sgpr(6, 2))); - assert_eq!(v.src, [vgpr(1, 1), vgpr(2, 1)]); - - // VOP3B: bits 14:8 hold the carry-out SGPR instead of abs/opsel. - let op = opcode(Encoding::Vop3, "v_div_scale_f32"); - let w0 = 1 | (6 << 8) | (u32::from(op) << 16); - let v = valu( - Encoding::Vop3, - "v_div_scale_f32", - &[w0, dw1([0x101, 0x102, 0x103], 0, 0)], - true, - ); - assert_eq!(v.carry, Some(sgpr(6, 2))); - assert_eq!(v.src, [vgpr(1, 1), vgpr(2, 1), vgpr(3, 1)]); - assert_eq!((v.abs, v.opsel), (0, 0)); - - // The literal of a nine-bit source field is the third dword. - let v = valu( - Encoding::Vop3, - "v_div_scale_f32", - &[ - 1 | (u32::from(op) << 16), - dw1([0x101, 0x102, 255], 0, 0), - 0x4120_0000, - ], - false, - ); - assert_eq!(v.src[2], Operand::Literal(0x4120_0000)); - - // v_readlane writes an SGPR; v_interp reads an attribute in src0. - let op = opcode(Encoding::Vop3, "v_readlane_b32"); - let v = valu( - Encoding::Vop3, - "v_readlane_b32", - &[dw0(op, 5, 0, 0, false), dw1([0x102, 3, 0], 0, 0)], - false, - ); - assert_eq!(v.dst, Some(sgpr(5, 1))); - assert_eq!(v.src, [vgpr(2, 1), sgpr(3, 1)]); - - let op = opcode(Encoding::Vop3, "v_interp_p1ll_f16"); - let code = 5 | (2 << 6) | (1 << 8); - let v = valu( - Encoding::Vop3, - "v_interp_p1ll_f16", - &[dw0(op, 1, 0, 0, false), dw1([code, 0x104, 0], 0, 0)], - false, - ); - assert_eq!( - v.src, - [ - Operand::Attr { - index: 5, - chan: 2, - high: true - }, - vgpr(4, 1) - ] - ); - } - - #[test] - fn vop3p_halves() { - let op = opcode(Encoding::Vop3p, "v_pk_add_f16"); - let v = valu( - Encoding::Vop3p, - "v_pk_add_f16", - &[ - dw0(op, 1, 7, 5, false) | (1 << 14), - dw1([0x101, 0x102, 0], 2, 5), - ], - false, - ); - assert_eq!(v.src, [vgpr(1, 1), vgpr(2, 1)]); - assert_eq!((v.neg, v.neg_hi, v.opsel, v.opsel_hi), (5, 7, 5, 6)); - - let op = opcode(Encoding::Vop3p, "v_pk_fma_f16"); - let v = valu( - Encoding::Vop3p, - "v_pk_fma_f16", - &[dw0(op, 1, 0, 0, false), dw1([0x101, 0x102, 0x103], 0, 0)], - false, - ); - assert_eq!(v.src.len(), 3); - - let op = opcode(Encoding::Vop3p, "v_fma_mix_f32"); - let v = valu( - Encoding::Vop3p, - "v_fma_mix_f32", - &[dw0(op, 1, 0, 0, false), dw1([0x101, 0x102, 0x103], 0, 0)], - false, - ); - assert_eq!(v.src.len(), 3); - } - - #[test] - fn interpolation() { - let op = u32::from(opcode(Encoding::Vintrp, "v_interp_p1_f32")); - let w0 = (0x32 << 26) | (op << 16) | (2 << 18) | (5 << 10) | (1 << 8) | 4; - let Fields::Vintrp { dst, src, attr } = - inst(Encoding::Vintrp, "v_interp_p1_f32", &[w0]).fields(false) - else { - panic!("not VINTRP"); - }; - assert_eq!(dst, vgpr(2, 1)); - assert_eq!(src, vgpr(4, 1)); - assert_eq!( - attr, - Operand::Attr { - index: 5, - chan: 1, - high: false - } - ); - - // The destination is the full 8-bit field at 25:18. - let w0 = (0x32 << 26) | (op << 16) | (1 << 25) | (2 << 18); - let Fields::Vintrp { dst, .. } = - inst(Encoding::Vintrp, "v_interp_p1_f32", &[w0]).fields(false) - else { - panic!("not VINTRP"); - }; - assert_eq!(dst, vgpr(130, 1)); - - // v_interp_mov's second field is a parameter, not a VGPR. - let Fields::Vintrp { src, .. } = inst( - Encoding::Vintrp, - "v_interp_mov_f32", - &[(0x32 << 26) | (1 << 8) | 1], - ) - .fields(false) else { - panic!("not VINTRP"); - }; - assert_eq!(src, Operand::Const(1)); - } - - #[test] - fn lds_operands() { - // ds_read2_b32 v[6:7], v1 offset0:2 offset1:3 gds - let Fields::Ds { - dst, - addr, - data, - offset0, - offset1, - gds, - } = inst( - Encoding::Ds, - "ds_read2_b32", - &[2 | (3 << 8) | (1 << 17), (6 << 24) | 1], - ) - .fields(false) - else { - panic!("not DS"); - }; - assert_eq!(dst, Some(vgpr(6, 2))); - assert_eq!(addr, Some(vgpr(1, 1))); - assert!(data.is_empty()); - assert_eq!((offset0, offset1, gds), (2, 3, true)); - - // A 128-bit store is one four-dword range, not four fields. - let Fields::Ds { dst, data, .. } = - inst(Encoding::Ds, "ds_write_b128", &[0, (2 << 8) | 1]).fields(false) - else { - panic!("not DS"); - }; - assert!(dst.is_none()); - assert_eq!(data, [vgpr(2, 4)]); - - // ds_append returns a value but takes no address. - let Fields::Ds { - dst, addr, data, .. - } = inst(Encoding::Ds, "ds_append", &[0, 3 << 24]).fields(false) - else { - panic!("not DS"); - }; - assert_eq!(dst, Some(vgpr(3, 1))); - assert!(addr.is_none()); - assert!(data.is_empty()); - - // GWS operations have neither an address nor data. - let Fields::Ds { - dst, addr, data, .. - } = inst(Encoding::Ds, "ds_gws_sema_v", &[0, 0]).fields(false) - else { - panic!("not DS"); - }; - assert!(dst.is_none() && addr.is_none() && data.is_empty()); - - let Fields::Ds { - dst, addr, data, .. - } = inst( - Encoding::Ds, - "ds_add_rtn_u32", - &[0, (4 << 24) | (6 << 8) | 5], - ) - .fields(false) - else { - panic!("not DS"); - }; - assert_eq!(dst, Some(vgpr(4, 1))); - assert_eq!(addr, Some(vgpr(5, 1))); - assert_eq!(data, [vgpr(6, 1)]); - - // Compare-and-swap and the two-address forms take both data fields. - let Fields::Ds { data, .. } = - inst(Encoding::Ds, "ds_cmpst_b32", &[0, (3 << 16) | (2 << 8) | 1]).fields(false) - else { - panic!("not DS"); - }; - assert_eq!(data, [vgpr(2, 1), vgpr(3, 1)]); - let Fields::Ds { dst, data, .. } = inst( - Encoding::Ds, - "ds_write2_b64", - &[0, (3 << 16) | (2 << 8) | 1], - ) - .fields(false) else { - panic!("not DS"); - }; - assert!(dst.is_none()); - assert_eq!(data, [vgpr(2, 2), vgpr(3, 2)]); - } - - #[test] - fn buffer_operands() { - let Fields::Buffer { - data, - addr, - rsrc, - soffset, - offset, - offen, - idxen, - format, - lds, - tfe, - cache, - } = inst( - Encoding::Mubuf, - "buffer_load_dwordx4", - &[0xE034_7010, 0x0102_0402], - ) - .fields(false) - else { - panic!("not a buffer instruction"); - }; - assert_eq!(data, Some(vgpr(4, 4))); - assert_eq!(addr, vgpr(2, 2)); - assert_eq!(rsrc, sgpr(8, 4)); - assert_eq!(soffset, sgpr(1, 1)); - assert_eq!(offset, 16); - assert!(offen && idxen && !lds && !tfe); - assert_eq!(format, None); - assert_eq!( - cache, - Cache { - glc: true, - slc: false, - dlc: false - } - ); - - // TFE returns one more dword; lds loads into shared memory. - let Fields::Buffer { data, tfe, .. } = inst( - Encoding::Mubuf, - "buffer_load_dword", - &[0, (1 << 23) | (4 << 8) | 2], - ) - .fields(false) else { - panic!("not a buffer instruction"); - }; - assert!(tfe); - assert_eq!(data, Some(vgpr(4, 2))); - let Fields::Buffer { lds, .. } = - inst(Encoding::Mubuf, "buffer_load_dword", &[1 << 16, 0]).fields(false) - else { - panic!("not a buffer instruction"); - }; - assert!(lds); - - // MTBUF's unified format; format_d16 halves 3d data. - let Fields::Buffer { - data, - addr, - rsrc, - soffset, - offset, - format, - lds, - .. - } = inst( - Encoding::Mtbuf, - "tbuffer_load_format_d16_xyzw", - &[ - (17 << 19) | 16 | (1 << 12) | (1 << 13), - (3 << 24) | (4 << 8) | 1 | (2 << 16), - ], - ) - .fields(false) - else { - panic!("not a buffer instruction"); - }; - assert_eq!(format, Some(17)); - assert_eq!(offset, 16); - assert!(!lds); - assert_eq!(data, Some(vgpr(4, 2))); - assert_eq!(addr, vgpr(1, 2)); - assert_eq!(rsrc, sgpr(8, 4)); - assert_eq!(soffset, sgpr(3, 1)); - - // Stores have no destination; the stored dwords are the data. - let Fields::Buffer { data, .. } = - inst(Encoding::Mubuf, "buffer_store_dwordx2", &[0, (4 << 8) | 1]).fields(false) - else { - panic!("not a buffer instruction"); - }; - assert_eq!(data, Some(vgpr(4, 2))); - } - - #[test] - fn image_operands() { - // image_sample_lz v[8:9], [v1,v5], s[16:23], s[4:7] dmask:0x7 d16: - // three channels pack into two dwords, and the NSA form lists the - // addresses one VGPR each. - let Fields::Image { - data, - addr, - rsrc, - sampler, - dmask, - dim, - unorm, - r128, - a16, - d16, - tfe, - lwe, - cache, - } = inst( - Encoding::Mimg, - "image_sample_lz", - &[0xF09C_070A, 0x8024_0801, 0x0000_0005], - ) - .fields(false) - else { - panic!("not an image instruction"); - }; - assert_eq!(data, vgpr(8, 2)); - assert_eq!(addr, [vgpr(1, 1), vgpr(5, 1)]); - assert_eq!(rsrc, sgpr(16, 8)); - assert_eq!(sampler, Some(sgpr(4, 4))); - assert_eq!((dmask, dim), (7, 1)); - assert!(!unorm && !r128 && !a16 && d16 && !tfe && !lwe); - assert_eq!(cache, Cache::default()); - - // Most flags at once: dim 3D has three coordinates and six gradients; - // the coordinates pack with a16 while the gradients stay whole dwords. - let w0 = 0xF000_0000 - | 0x0F00 - | 0x10 - | (1 << 25) - | (1 << 16) - | (1 << 15) - | (1 << 13) - | (1 << 12) - | (1 << 7); - let w1 = 0xC062_0401; - let Fields::Image { - data, - addr, - rsrc, - sampler, - dim, - unorm, - r128, - a16, - d16, - tfe, - lwe, - cache, - .. - } = inst(Encoding::Mimg, "image_sample_d", &[w0, w1]).fields(false) - else { - panic!("not an image instruction"); - }; - assert_eq!(dim, 2); - assert!(unorm && r128 && a16 && d16 && tfe && !lwe); - assert_eq!( - cache, - Cache { - glc: true, - slc: true, - dlc: true - } - ); - assert_eq!(rsrc, sgpr(8, 4)); - assert_eq!(sampler, Some(sgpr(12, 4))); - assert_eq!(data, vgpr(4, 3)); - assert_eq!(addr, [vgpr(1, 8)]); - - // lwe appends a dword of its own. - let w0 = 0xF000_0000 | 0x10 | (1 << 8) | (1 << 17); - let Fields::Image { data, lwe, .. } = - inst(Encoding::Mimg, "image_load", &[w0, 0x0002_0401]).fields(false) - else { - panic!("not an image instruction"); - }; - assert!(lwe); - assert_eq!(data, vgpr(4, 2)); - - // The NSA address dwords carry four VGPRs each. - let w0 = 0xF000_0000 | 0x6 | 0x10 | 0x0F00; - let Fields::Image { addr, .. } = inst( - Encoding::Mimg, - "image_sample_d", - &[w0, 0x0002_0401, 0x0403_0201, 0x0807_0605, 0], - ) - .fields(false) else { - panic!("not an image instruction"); - }; - assert_eq!( - addr, - [ - vgpr(1, 1), - vgpr(1, 1), - vgpr(2, 1), - vgpr(3, 1), - vgpr(4, 1), - vgpr(5, 1), - vgpr(6, 1), - vgpr(7, 1), - vgpr(8, 1) - ] - ); - - // Loads take no sampler. - let Fields::Image { sampler, .. } = - inst(Encoding::Mimg, "image_load", &[0, 0]).fields(false) - else { - panic!("not an image instruction"); - }; - assert_eq!(sampler, None); - } - - #[test] - fn flat_global_and_scratch() { - // flat_load_dwordx3 v[4:6], v[2:3] inst_offset:2047, every cache flag - let w0 = 0xDC00_0000 | 2047 | (1 << 12) | (1 << 13) | (1 << 16) | (1 << 17); - let Fields::Flat { - dst, - addr, - data, - offset, - lds, - cache, - .. - } = inst(Encoding::Flat, "flat_load_dwordx3", &[w0, 0x0400_0402]).fields(false) - else { - panic!("not FLAT"); - }; - assert_eq!(dst, Some(vgpr(4, 3))); - assert_eq!(addr, Some(vgpr(2, 2))); - assert_eq!(data, None); - assert_eq!(offset, 2047); - assert!(lds); - assert_eq!( - cache, - Cache { - glc: true, - slc: true, - dlc: true - } - ); - - // GLOBAL's offset is 12 bits, signed. - let Fields::Flat { offset, .. } = inst( - Encoding::Global, - "global_load_dwordx2", - &[0xDC00_0FFF, (4 << 8) | 2], - ) - .fields(false) else { - panic!("not GLOBAL"); - }; - assert_eq!(offset, -1); - let Fields::Flat { offset, .. } = - inst(Encoding::Global, "global_load_dwordx2", &[0xDC00_07FF, 0]).fields(false) - else { - panic!("not GLOBAL"); - }; - assert_eq!(offset, 2047); - - // A null saddr adds a VGPR to the address; scratch always has 32 bits. - let Fields::Flat { - addr, saddr, data, .. - } = inst( - Encoding::Global, - "global_load_dwordx2", - &[0, (125 << 16) | (4 << 8) | 2], - ) - .fields(false) - else { - panic!("not GLOBAL"); - }; - assert_eq!(addr, Some(vgpr(2, 2))); - assert_eq!(saddr, Some(sgpr(125, 2))); - assert_eq!(data, None); - - let Fields::Flat { addr, saddr, .. } = inst( - Encoding::Scratch, - "scratch_load_dword", - &[0, (125 << 16) | (4 << 8) | 1], - ) - .fields(false) else { - panic!("not SCRATCH"); - }; - assert_eq!(addr, Some(vgpr(1, 1))); - assert_eq!(saddr, Some(sgpr(125, 1))); - let Fields::Flat { addr, saddr, .. } = inst( - Encoding::Scratch, - "scratch_load_dword", - &[0, (3 << 16) | (4 << 8) | 1], - ) - .fields(false) else { - panic!("not SCRATCH"); - }; - assert_eq!(addr, None); - assert_eq!(saddr, Some(sgpr(3, 1))); - - // A store has no destination; a returning atomic keeps the old value. - let Fields::Flat { dst, data, .. } = - inst(Encoding::Global, "global_store_dword", &[0, (4 << 8) | 2]).fields(false) - else { - panic!("not GLOBAL"); - }; - assert!(dst.is_none()); - assert_eq!(data, Some(vgpr(4, 1))); - let Fields::Flat { dst, data, .. } = inst( - Encoding::Global, - "global_atomic_cmpswap_x2", - &[1 << 16, (6 << 24) | (4 << 8) | 1], - ) - .fields(false) else { - panic!("not GLOBAL"); - }; - assert_eq!(dst, Some(vgpr(6, 2))); - assert_eq!(data, Some(vgpr(4, 4))); - } - - #[test] - fn exports() { - let Fields::Exp { - target, - src, - compr, - done, - vm, - } = inst_raw(Encoding::Exp, 0, &[0xF800_1C0F, 0x0000_0302]).fields(false) - else { - panic!("not EXP"); - }; - assert_eq!(target, 0); - assert_eq!( - src, - [ - Some(vgpr(2, 1)), - Some(vgpr(2, 1)), - Some(vgpr(3, 1)), - Some(vgpr(3, 1)) - ] - ); - assert!(compr && done && vm); - - let Fields::Exp { - target, - src, - compr, - done, - vm, - } = inst_raw( - Encoding::Exp, - 0, - &[ - 0xF800_0000 | 0b0101 | (12 << 4), - 4 | (5 << 8) | (6 << 16) | (7 << 24), - ], - ) - .fields(false) - else { - panic!("not EXP"); - }; - assert_eq!(target, 12); - assert_eq!(src, [Some(vgpr(4, 1)), None, Some(vgpr(6, 1)), None]); - assert!(!compr && !done && !vm); + whole + 2 * derivs + packed } } diff --git a/crates/victory-shader/src/gfx10/sp3.rs b/crates/victory-shader/src/gfx10/sp3.rs index baf0e82..0ca5ab4 100644 --- a/crates/victory-shader/src/gfx10/sp3.rs +++ b/crates/victory-shader/src/gfx10/sp3.rs @@ -137,12 +137,6 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { cache, } => { if let Some(data) = data { - let data = match (name, data) { - ("s_atc_probe" | "s_atc_probe_buffer", Operand::Literal(imm)) => { - atc_immediate(*imm) - } - _ => data.to_string(), - }; let off = match (soffset, offset) { (Operand::Scalar { code: NULL, .. }, 0) => soffset.to_string(), (Operand::Scalar { code: NULL, .. }, _) => { @@ -341,15 +335,6 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { out } -/// `s_atc_probe` immediate: 0..=64 in decimal, larger values in hex. -fn atc_immediate(imm: u32) -> String { - if imm <= 64 { - imm.to_string() - } else { - format!("0x{imm:x}") - } -} - /// Cache flags; images write `dlc` first. fn flags(out: &mut String, cache: &Cache, dlc_first: bool) { let dlc = (cache.dlc, " dlc"); @@ -675,7 +660,7 @@ fn valu(name: &str, v: &Valu, encoding: Encoding) -> String { #[cfg(test)] mod tests { - use crate::gfx10::{Cache, Fields, Operand, decode}; + use crate::gfx10::{Fields, Operand, decode}; /// Text of each instruction in `words` (a straight-line program). fn texts(words: &[u32], wave64: bool) -> Vec { @@ -715,69 +700,6 @@ mod tests { ); } - /// `s_atc_probe` / `s_atc_probe_buffer`: SDATA is a 7-bit immediate, the - /// buffer resource is 4 dwords, and GLC/DLC are not operands. - /// - /// Words checked with `llvm-mc -arch=amdgcn -mcpu=gfx1030 --disassemble`. - /// The offset keeps this printer's 6-digit hex (`0x000064`, not `0x64`). - #[test] - fn atc_probe_immediate_is_not_a_register() { - let cases = [ - ( - [0xF498_01C2, 0xFA00_0064], - "s_atc_probe 7, s[4:5], 0x000064", - Operand::Literal(7), - Operand::Scalar { code: 4, dwords: 2 }, - ), - ( - [0xF498_1FF4, 0x0A00_0001], - "s_atc_probe 0x7f, s[104:105], s5 offset:0x000001", - Operand::Literal(0x7f), - Operand::Scalar { - code: 104, - dwords: 2, - }, - ), - ( - [0xF498_0000, 0xFA00_0000], - "s_atc_probe 0, s[0:1], null", - Operand::Literal(0), - Operand::Scalar { code: 0, dwords: 2 }, - ), - ( - [0xF49C_01C4, 0xFA00_0020], - "s_atc_probe_buffer 7, s[8:11], 0x000020", - Operand::Literal(7), - Operand::Scalar { code: 8, dwords: 4 }, - ), - ( - [0xF499_41C2, 0xFA00_0000], - "s_atc_probe 7, s[4:5], null", - Operand::Literal(7), - Operand::Scalar { code: 4, dwords: 2 }, - ), - ]; - for (words, text, data, base) in cases { - assert_eq!(one(&words, false), text, "{words:08x?}"); - assert_eq!(one(&words, true), text, "{words:08x?}"); - let mut code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - code.extend(0xBF81_0000u32.to_le_bytes()); - let inst = &decode(&code).unwrap()[0]; - let Fields::Smem { - data: got, - base: got_base, - cache, - .. - } = inst.fields(false) - else { - panic!("not an SMEM instruction"); - }; - assert_eq!(got, Some(data), "{words:08x?}"); - assert_eq!(got_base, base, "{words:08x?}"); - assert_eq!(cache, Cache::default(), "{words:08x?}"); - } - } - #[test] fn lane_masks_follow_the_wave_size() { let cmp = [0x7C08_06F0]; // v_cmp_gt_f32 with 0.5 and v3 diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index c35d410..09b1f8e 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -187,8 +187,8 @@ pub struct Io { pub inputs: Vec<(Value, Input)>, pub interps: Vec<(Site, Interp)>, pub exports: Vec, - /// How many SGPRs the hardware initializes on entry - /// ([`StageIo::initialized_sgprs`](crate::native::StageIo::initialized_sgprs)). + /// Compute: how many SGPRs the hardware initializes + /// ([`ComputeIo::initialized_sgprs`](crate::native::ComputeIo::initialized_sgprs)). pub initialized_sgprs: Option, } @@ -334,7 +334,10 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { let mut io = Io { inputs: inputs.clone(), - initialized_sgprs: native.io.initialized_sgprs(), + initialized_sgprs: match &native.io { + StageIo::Cs(cs) => Some(cs.initialized_sgprs()), + _ => None, + }, ..Io::default() }; let defs: std::collections::HashMap = p @@ -619,7 +622,6 @@ mod tests { used: vec![], io: StageIo::Ps { inputs, - rsrc2: 0, input_addr, db_shader_control: 0, patches: Vec::::new(), diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 5c6393c..0b8fd9c 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -179,11 +179,7 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result Result| regs.into_iter().map(|r| (r, NONE)).collect(); blocks[b].insts.push(Inst { machine, fields, - reads, - writes, + reads: unset(reads), + writes: unset(writes), }); } } @@ -249,7 +246,6 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result Option<(bool, u8, u8, u32)> { let Fields::Valu(v) = fields else { return None }; - if v.abs != 0 - || v.neg != 0 - || v.opsel != 0 - || v.clamp - || v.omod != 0 - || v.sdwa.is_some() - || v.dpp.is_some() - { + if v.abs != 0 || v.neg != 0 || v.opsel != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some() || v.dpp.is_some() { return None; } let lane = |op: &Operand| match *op { @@ -275,14 +264,10 @@ fn unspill( _ => None, }; match (inst.name()?, v.dst?, v.src.as_slice()) { - ("v_writelane_b32", Operand::Vector { reg, .. }, [Operand::Scalar { code, .. }, k]) - if *code < 105 => - { + ("v_writelane_b32", Operand::Vector { reg, .. }, [Operand::Scalar { code, .. }, k]) if *code < 105 => { Some((true, reg, *code, lane(k)?)) } - ("v_readlane_b32", Operand::Scalar { code, .. }, [Operand::Vector { reg, .. }, k]) - if code < 105 => - { + ("v_readlane_b32", Operand::Scalar { code, .. }, [Operand::Vector { reg, .. }, k]) if code < 105 => { Some((false, *reg, code, lane(k)?)) } _ => None, @@ -295,23 +280,37 @@ fn unspill( let mut used = [false; 128]; let mut parks: Vec> = Vec::with_capacity(list.len()); let mut written: Vec> = Vec::with_capacity(list.len()); + let mut read: Vec> = Vec::with_capacity(list.len()); for inst in list.iter() { - let Some(name) = inst.name() else { - return Vec::new(); - }; + let Some(name) = inst.name() else { return Vec::new() }; let fields = inst.fields(wave64); let park = parked(inst, &fields); let Ok(effects) = effects(inst, &fields, name, lanes, vgprs) else { return Vec::new(); }; let mut codes = Vec::new(); + let mut from = Vec::new(); if let Some((reads, writes)) = effects { - for w in &writes { - if let Reg::S(c) = w.0 { + for ® in &writes { + if let Reg::S(c) = reg { codes.push(c); } } - for reg in reads.into_iter().chain(writes).map(|r| r.0) { + for ® in &reads { + if let Reg::S(c) = reg { + from.push(c); + } + } + // An M0-relative read (`v_movrels_b32`) names every VGPR from its + // base up; the compiler indexes a small array with it, never the + // lanes it parks scalars in, so it does not make those VGPRs + // ordinary ones. (Relative writes still do.) + let relative = name == "v_movrels_b32"; + let n_reads = reads.len(); + for (k, reg) in reads.into_iter().chain(writes).enumerate() { + if relative && k < n_reads && matches!(reg, Reg::V(_)) { + continue; + } match reg { Reg::S(c) => used[usize::from(c)] = true, Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true, @@ -322,6 +321,7 @@ fn unspill( } parks.push(park); written.push(codes); + read.push(from); } for (i, park) in parks.iter_mut().enumerate() { if park.is_some_and(|p| other[usize::from(p.1)]) { @@ -364,35 +364,39 @@ fn unspill( } None } else { - let j = i + 1; - (j < list.len() && !leader(j) && parks[j] == Some((false, reg, code + 1, lane + 1))) - .then_some(j) + // The second restore may come a few instructions later (the + // compiler schedules other work between the two): the pair is + // restored at the first, so nothing between may read or write + // the second register, write the first, or save into the lanes. + let mut j = i + 1; + while j < list.len() && !leader(j) { + if parks[j] == Some((false, reg, code + 1, lane + 1)) { + return Some(j); + } + if parks[j].is_some_and(|p| p.0 && p.1 == reg && (p.3 == lane || p.3 == lane + 1)) + || written[j].contains(&code) + || written[j].contains(&(code + 1)) + || read[j].contains(&(code + 1)) + { + return None; + } + j += 1; + } + None } }; let mut pairs: Vec<(u8, u32)> = Vec::new(); for &(reg, lane) in &slots { - if !wave64 - || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) - || !slots.contains(&(reg, lane + 1)) - { + if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) { continue; } - let lower: Vec = (0..list.len()) - .filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))) - .collect(); - let upper = parks - .iter() - .flatten() - .filter(|p| (p.1, p.3) == (reg, lane + 1)) - .count(); + let lower: Vec = (0..list.len()).filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))).collect(); + let upper = parks.iter().flatten().filter(|p| (p.1, p.3) == (reg, lane + 1)).count(); let partners: Vec> = lower.iter().map(|&i| partner(i)).collect(); let mut distinct: Vec = partners.iter().flatten().copied().collect(); distinct.sort_unstable(); distinct.dedup(); - if partners.iter().all(Option::is_some) - && distinct.len() == lower.len() - && upper == lower.len() - { + if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() { pairs.push((reg, lane)); } } @@ -409,10 +413,7 @@ fn unspill( free[past..255].fill(true); let mut codes: Vec<((u8, u32), u8)> = Vec::new(); for &(reg, lane) in &pairs { - let at = (108..123) - .chain((0..104).rev()) - .chain(past..254) - .find(|&c| free[c] && free[c + 1]); + let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]); // Not enough spare codes: leave the program as it is. let Some(c) = at else { return Vec::new() }; (free[c], free[c + 1]) = (false, false); @@ -423,11 +424,7 @@ fn unspill( if codes.iter().any(|c| c.0 == slot) { continue; } - let Some(c) = (108..=123) - .chain((0..105).rev()) - .chain(past..255) - .find(|&c| free[c]) - else { + let Some(c) = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c]) else { return Vec::new(); }; free[c] = false; @@ -445,22 +442,16 @@ fn unspill( // `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code // from `PARKED` up does not fit the word: s0 stands in for it there. let field = |code: u8| if code < PARKED { u32::from(code) } else { 0 }; - let mov = |wide: bool, dst: u8, src: u8| { - 0xBE80_0000 | field(dst) << 16 | (3 + u32::from(wide)) << 8 | field(src) - }; + let mov = |wide: bool, dst: u8, src: u8| 0xBE80_0000 | field(dst) << 16 | (3 + u32::from(wide)) << 8 | field(src); const NOP: u32 = 0xBF80_0000; let mut edits: Vec<(usize, Option<(bool, u8, u8)>)> = Vec::new(); for i in 0..list.len() { let Some((save, reg, code, lane)) = parks[i] else { continue; }; - let Some(slot) = code_of(reg, lane) else { - return Vec::new(); - }; + let Some(slot) = code_of(reg, lane) else { return Vec::new() }; if pairs.contains(&(reg, lane)) { - let Some(j) = partner(i) else { - return Vec::new(); - }; + let Some(j) = partner(i) else { return Vec::new() }; // A save moves the pair where its second half is saved; a // restore where its first half is restored. let (at, gone) = if save { (j, i) } else { (i, j) }; @@ -478,13 +469,7 @@ fn unspill( for (i, edit) in edits { match edit { Some((wide, dst, src)) => { - put( - list, - i, - gfx10::Encoding::Sop1, - 3 + u16::from(wide), - mov(wide, dst, src), - ); + put(list, i, gfx10::Encoding::Sop1, 3 + u16::from(wide), mov(wide, dst, src)); moves.push((i, dst, src)); } None => put(list, i, gfx10::Encoding::Sopp, 0, NOP), @@ -607,10 +592,7 @@ pub(crate) fn thread_edges( pub(crate) fn without_early_outs(p: &Program) -> Option { let ends = |b: usize| { p.blocks[b].exit == Exit::End - && p.blocks[b] - .insts - .iter() - .all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) + && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) }; let mut blocks = p.blocks.clone(); let mut any = false; @@ -618,12 +600,7 @@ pub(crate) fn without_early_outs(p: &Program) -> Option { let Exit::Branch { taken, not_taken } = block.exit else { continue; }; - if ends(taken) - && block - .insts - .last() - .is_some_and(|i| i.name() == "s_cbranch_execz") - { + if ends(taken) && block.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") { block.insts.pop(); block.exit = Exit::Jump(not_taken); any = true; @@ -659,15 +636,11 @@ pub(crate) fn without_early_outs(p: &Program) -> Option { /// the join may have other ways in (an inner branch that ends together with an outer one). /// That leaves out most of the skips of the title's large lighting programs, whose bodies /// are then code every lane runs. -#[allow(clippy::needless_range_loop)] pub(crate) fn without_skips(p: &Program, deep: bool) -> Option { let n = p.blocks.len(); let ends = |b: usize| { p.blocks[b].exit == Exit::End - && p.blocks[b] - .insts - .iter() - .all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) + && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) }; // Scalars moved from register to register (a scalar the compiler parked in a VGPR lane // comes back by such a move, `unspill`) are the value they copy. @@ -691,11 +664,7 @@ pub(crate) fn without_skips(p: &Program, deep: bool) -> Option { for inst in &block.insts { if matches!(inst.name(), "s_mov_b32" | "s_mov_b64") && inst.reads.len() == inst.writes.len() - && inst - .reads - .iter() - .chain(&inst.writes) - .all(|r| matches!(r.0, Reg::S(_))) + && inst.reads.iter().chain(&inst.writes).all(|r| matches!(r.0, Reg::S(_))) { copy.extend(inst.writes.iter().zip(&inst.reads).map(|(w, r)| (w.1, r.1))); } @@ -762,19 +731,9 @@ pub(crate) fn without_skips(p: &Program, deep: bool) -> Option { if !scalar || deep && !live.contains(&phi.value) { continue; } - let before: Vec = join - .preds - .iter() - .zip(&phi.args) - .filter(|(q, _)| **q == b) - .map(|(_, a)| root(*a)) - .collect(); - let within = join - .preds - .iter() - .zip(&phi.args) - .filter(|(q, _)| inside[**q]) - .map(|(_, a)| root(*a)); + let before: Vec = + join.preds.iter().zip(&phi.args).filter(|(q, _)| **q == b).map(|(_, a)| root(*a)).collect(); + let within = join.preds.iter().zip(&phi.args).filter(|(q, _)| inside[**q]).map(|(_, a)| root(*a)); if within.into_iter().any(|a| !before.contains(&a)) { return None; } @@ -793,11 +752,7 @@ pub(crate) fn without_skips(p: &Program, deep: bool) -> Option { let Exit::Branch { taken, not_taken } = p.blocks[b].exit else { continue; }; - if !p.blocks[b] - .insts - .last() - .is_some_and(|i| i.name() == "s_cbranch_execz") - { + if !p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") { continue; } if ends(taken) || skipped(b, taken, not_taken).is_some() { @@ -1206,9 +1161,8 @@ const DROPPED: &[&str] = &[ "v_clrexcp", ]; -/// Registers read, registers written, each with a placeholder value the -/// SSA pass fills in. -type Effects = (Vec<(Reg, Value)>, Vec<(Reg, Value)>); +/// Registers read, registers written. +type Effects = (Vec, Vec); /// The registers `inst` of `p` reads as operands: its reads without the old /// value of a VGPR it only writes. @@ -1217,7 +1171,7 @@ pub(crate) fn operand_reads(p: &Program, inst: &Inst) -> Vec { effects(&inst.machine, &inst.fields, inst.name(), lanes, p.vgprs) .ok() .flatten() - .map_or_else(Vec::new, |e| e.0.into_iter().map(|r| r.0).collect()) + .map_or_else(Vec::new, |e| e.0) } /// Registers an instruction reads and writes, one per dword, or `None` if @@ -1236,9 +1190,9 @@ fn effects( offset: inst.offset, what: name, }; - let mask = |code: u8| (0..lanes).map(move |i| (Reg::S(code + i), NONE)); + let mask = |code: u8| (0..lanes).map(move |i| Reg::S(code + i)); let (mut r, mut w) = (Vec::new(), Vec::new()); - let regs = |op: &Operand, out: &mut Vec<(Reg, Value)>| { + let regs = |op: &Operand, out: &mut Vec| { add_regs(op, lanes, out).map_err(|_| ShaderError::Isa { offset: inst.offset, reason: "register range out of bounds", @@ -1273,21 +1227,21 @@ fn effects( || name.starts_with("s_cselect_") || name.starts_with("s_cmov_") { - r.push((Reg::Scc, NONE)); + r.push(Reg::Scc); } if name.contains("saveexec") || name.contains("wrexec") { r.extend(mask(EXEC)); w.extend(mask(EXEC)); } if writes_scc(inst.encoding, name) { - w.push((Reg::Scc, NONE)); + w.push(Reg::Scc); } } Fields::Sopp { .. } => match name { - "s_cbranch_scc0" | "s_cbranch_scc1" => r.push((Reg::Scc, NONE)), + "s_cbranch_scc0" | "s_cbranch_scc1" => r.push(Reg::Scc), "s_cbranch_vccz" | "s_cbranch_vccnz" => r.extend(mask(VCC)), "s_cbranch_execz" | "s_cbranch_execnz" => r.extend(mask(EXEC)), - "s_sendmsg" | "s_sendmsghalt" => r.push((Reg::S(M0), NONE)), + "s_sendmsg" | "s_sendmsghalt" => r.push(Reg::S(M0)), "s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" @@ -1333,9 +1287,9 @@ fn effects( _ => (false, false), }; // v[reg + M0] for any M0 that stays inside the program's VGPRs. - let indexed = |op: &Operand, out: &mut Vec<(Reg, Value)>| match *op { + let indexed = |op: &Operand, out: &mut Vec| match *op { Operand::Vector { reg, .. } if u16::from(reg) < vgprs => { - out.extend((u16::from(reg)..vgprs).map(|r| (Reg::V(r as u8), NONE))); + out.extend((u16::from(reg)..vgprs).map(|r| Reg::V(r as u8))); Ok(()) } _ => Err(ShaderError::Isa { @@ -1380,12 +1334,12 @@ fn effects( _ => {} } if name.starts_with("v_interp_") || src_indexed || dst_indexed { - r.push((Reg::S(M0), NONE)); + r.push(Reg::S(M0)); } } Fields::Vintrp { dst, src, .. } => { regs(src, &mut r)?; - r.push((Reg::S(M0), NONE)); + r.push(Reg::S(M0)); regs(dst, &mut w)?; } Fields::Ds { @@ -1406,7 +1360,7 @@ fn effects( || name.contains("addtid") || matches!(name, "ds_ordered_count" | "ds_append" | "ds_consume") { - r.push((Reg::S(M0), NONE)); + r.push(Reg::S(M0)); } } Fields::Buffer { @@ -1426,7 +1380,7 @@ fn effects( regs(rsrc, &mut r)?; regs(soffset, &mut r)?; if *lds { - r.push((Reg::S(M0), NONE)); + r.push(Reg::S(M0)); } if let Some(d) = data { if name.contains("_load_") { @@ -1560,7 +1514,7 @@ fn atomic_result(data: &Operand, name: &str) -> Operand { /// Appends the register dwords an operand names; reading `vccz`, `execz`, /// `scc` or `lds_direct` reads the register behind it. -fn add_regs(op: &Operand, lanes: u8, out: &mut Vec<(Reg, Value)>) -> Result<(), ()> { +fn add_regs(op: &Operand, lanes: u8, out: &mut Vec) -> Result<(), ()> { match *op { Operand::Scalar { code, .. } if code == gfx10::NULL => {} Operand::Scalar { code, dwords } => { @@ -1571,18 +1525,18 @@ fn add_regs(op: &Operand, lanes: u8, out: &mut Vec<(Reg, Value)>) -> Result<(), if end > limit { return Err(()); } - out.extend((code..end as u8).map(|c| (Reg::S(c), NONE))); + out.extend((u16::from(code)..end).map(|c| Reg::S(c as u8))); } Operand::Vector { reg, dwords } => { if u16::from(reg) + u16::from(dwords) > 256 { return Err(()); } - out.extend((0..dwords).map(|i| (Reg::V(reg + i), NONE))); + out.extend((0..dwords).map(|i| Reg::V(reg + i))); } - Operand::Const(251) => out.extend((0..lanes).map(|i| (Reg::S(VCC + i), NONE))), - Operand::Const(252) => out.extend((0..lanes).map(|i| (Reg::S(EXEC + i), NONE))), - Operand::Const(253) => out.push((Reg::Scc, NONE)), - Operand::Const(254) => out.push((Reg::S(M0), NONE)), + Operand::Const(251) => out.extend((0..lanes).map(|i| Reg::S(VCC + i))), + Operand::Const(252) => out.extend((0..lanes).map(|i| Reg::S(EXEC + i))), + Operand::Const(253) => out.push(Reg::Scc), + Operand::Const(254) => out.push(Reg::S(M0)), Operand::Const(_) | Operand::Literal(_) | Operand::Attr { .. } => {} } Ok(()) @@ -1622,11 +1576,7 @@ mod tests { fn skips(p: &Program) -> usize { p.blocks .iter() - .filter(|b| { - b.insts - .last() - .is_some_and(|i| i.name() == "s_cbranch_execz") - }) + .filter(|b| b.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz")) .count() } diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 2038bef..4c267e1 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -35,7 +35,6 @@ //! mask, u8 attribute (v_interp `attr`), u8 default, u8 second //! row (of a packed pair), u8 parameter slot, u8 flags (bit 0 //! flat, 1 linear, 3 fp16, 4 fp16 packed); E+0x124 u32 count -//! E+0x128 u32 SPI_SHADER_PGM_RSRC2_PS //! E+0x134 u32 SPI_PS_INPUT_ADDR, E+0x138 u32 DB_SHADER_CONTROL //! E+0x148 u32 export patch size (dwords), E+0x14c 8 patches, one per //! MRT: u32 code offset (dwords, -1 none), then the export code @@ -103,7 +102,6 @@ const ENTRY_SIZE: u64 = 20; const MAX_SEMANTICS: u32 = 32; const PS_INPUTS: usize = 0x24; const PS_INPUT_COUNT: usize = 0x124; -const PS_RSRC2: usize = 0x128; const PS_INPUT_ADDR: usize = 0x134; const PS_DB_SHADER_CONTROL: usize = 0x138; const PS_PATCH_SIZE: usize = 0x148; @@ -262,8 +260,6 @@ pub enum StageIo { }, Ps { inputs: Vec, - /// `SPI_SHADER_PGM_RSRC2_PS`: user SGPRs and enabled hardware SGPRs. - rsrc2: u32, /// `SPI_PS_INPUT_ADDR`: which system values arrive in VGPRs. input_addr: u32, /// `DB_SHADER_CONTROL`: depth export, kill. @@ -274,33 +270,6 @@ pub enum StageIo { Ms(MeshIo), } -impl StageIo { - /// How many general SGPRs (`s0..`) the hardware initializes on entry, when - /// the stage's `PGM_RSRC2` register is read. Registers at or above this - /// count hold whatever the previous wave left. - pub fn initialized_sgprs(&self) -> Option { - match self { - Self::Cs(cs) => Some(cs.initialized_sgprs()), - Self::Ps { rsrc2, .. } => Some(ps_initialized_sgprs(*rsrc2)), - _ => None, - } - } -} - -/// SGPRs the hardware initializes for a pixel shader from -/// `SPI_SHADER_PGM_RSRC2_PS`: user SGPRs (bits 1-5, plus bit 28 as MSB), -/// `prim_mask` (always present), `wave_cnt` (bit 7), POPS collision wave id -/// (bit 25), intrawave collisions (bit 26), and the scratch wave offset -/// (bit 0). -pub fn ps_initialized_sgprs(rsrc2: u32) -> u8 { - let user = ((rsrc2 >> 1) & 0x1F) | (((rsrc2 >> 28) & 1) << 5); - let scratch = rsrc2 & 1; - let wave_cnt = (rsrc2 >> 7) & 1; - let pops_collision = (rsrc2 >> 25) & 1; - let pops_intrawave = (rsrc2 >> 26) & 1; - (user + 1 + wave_cnt + pops_collision + pops_intrawave + scratch) as u8 -} - /// A mesh program's outputs and limits. It runs as one hardware NGG stage: /// lane n of the group (`threads` lanes) exports vertex n (`exp pos`, /// `exp param`) and primitive n (`exp prim`). @@ -477,14 +446,63 @@ fn unpack(blob: &[u8]) -> Result, ShaderError> { } let stream = bytes(blob, XBCH_HEADER as u64, packed).ok_or(Malformed("XBCH stream out of bounds"))?; - let out = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(stream, unpacked as usize) - .map_err(|_| Malformed("XBCH stream does not inflate to its stated size"))?; - if out.len() as u64 != unpacked { - return Err(Malformed("XBCH stream does not inflate to its stated size")); - } + let out = inflate_zlib_exact(stream, unpacked as usize) + .ok_or(Malformed("XBCH stream does not inflate to its stated size"))?; Ok(out) } +/// Inflates a zlib stream incrementally up to `expected` bytes, rejecting +/// truncated, corrupt, under-filled, or oversized streams without eagerly +/// allocating the full declared size up front. +fn inflate_zlib_exact(source: &[u8], expected: usize) -> Option> { + let mut state = zlib_rs::Inflate::new(true, 15); + let mut out = Vec::new(); + let (mut in_pos, mut out_pos) = (0usize, 0usize); + loop { + if out_pos == expected { + let mut extra = [0u8; 1]; + let status = state + .decompress( + &source[in_pos..], + &mut extra, + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + return (status == zlib_rs::Status::StreamEnd + && state.total_out() as usize == expected) + .then_some(out); + } + if out_pos == out.len() { + let next_len = if out.is_empty() { + expected.min(source.len().saturating_mul(4).max(4096)) + } else { + out.len().saturating_mul(2).min(expected) + }; + out.resize(next_len, 0); + } + let status = state + .decompress( + &source[in_pos..], + &mut out[out_pos..], + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + let next_in = state.total_in() as usize; + let next_out = state.total_out() as usize; + match status { + zlib_rs::Status::StreamEnd => { + out.truncate(next_out); + return (next_out == expected).then_some(out); + } + zlib_rs::Status::Ok if next_in != in_pos || next_out != out_pos => { + in_pos = next_in; + out_pos = next_out; + } + zlib_rs::Status::Ok | zlib_rs::Status::BufError => return None, + } + } +} + fn programs(fssm: &[u8]) -> Result, ShaderError> { if fssm.get(0..4) != Some(b"FSSM") { return Err(Malformed("native blob lacks FSSM magic")); @@ -636,7 +654,6 @@ fn ps_io(data: &[u8], code_len: usize) -> Result { } Ok(StageIo::Ps { inputs, - rsrc2: u32_at(data, PS_RSRC2)?, input_addr: u32_at(data, PS_INPUT_ADDR)?, db_shader_control: u32_at(data, PS_DB_SHADER_CONTROL)?, patches, @@ -761,12 +778,15 @@ mod tests { } fn xbch(unpacked: &[u8]) -> Vec { - let stream = miniz_oxide::deflate::compress_to_vec_zlib(unpacked, 6); + let mut buf = vec![0u8; zlib_rs::compress_bound(unpacked.len())]; + let (stream, rc) = + zlib_rs::compress_slice(&mut buf, unpacked, zlib_rs::DeflateConfig::new(6)); + assert_eq!(rc, zlib_rs::ReturnCode::Ok); let mut out = b"XBCH".to_vec(); out.extend_from_slice(&XBCH_VERSION.to_le_bytes()); out.extend_from_slice(&(stream.len() as u64).to_le_bytes()); out.extend_from_slice(&(unpacked.len() as u64).to_le_bytes()); - out.extend_from_slice(&stream); + out.extend_from_slice(stream); out } @@ -817,7 +837,6 @@ mod tests { used: vec![], io: StageIo::Ps { inputs: vec![], - rsrc2: 0, input_addr: 0, db_shader_control: 0, patches: vec![], @@ -887,7 +906,6 @@ mod tests { // TEXCOORD in row 1 (xy), read as attr0, flat. blob[e + PS_INPUTS..][..8].copy_from_slice(&[6, 1, 3, 0, 0, 0, 1, 1]); blob[e + PS_INPUT_COUNT..][..4].copy_from_slice(&1u32.to_le_bytes()); - blob[e + PS_RSRC2..][..4].copy_from_slice(&0x14u32.to_le_bytes()); blob[e + PS_INPUT_ADDR..][..4].copy_from_slice(&2u32.to_le_bytes()); blob[e + PS_PATCH_SIZE..][..4].copy_from_slice(&2u32.to_le_bytes()); // MRT1 at dword 1: the 32_ABGR variant is `exp mrt1 v0-v3 done`. @@ -899,7 +917,6 @@ mod tests { let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; let StageIo::Ps { inputs, - rsrc2, input_addr, patches, .. @@ -917,7 +934,7 @@ mod tests { pack2: false, row2: 0, }; - assert_eq!((&inputs[..], *rsrc2, *input_addr), (&[input][..], 0x14, 2)); + assert_eq!((&inputs[..], *input_addr), (&[input][..], 2)); assert_eq!(patches.len(), 1); assert_eq!((patches[0].mrt, patches[0].offset), (1, 1)); let patched = p.patched_code(); @@ -1014,39 +1031,6 @@ mod tests { assert_eq!(cs.initialized_sgprs(), 11); } - #[test] - fn ps_initialized_sgprs_covers_user_system_and_scratch() { - // 10 user SGPRs (s0..=s9) + prim_mask (s10): 11. - assert_eq!(ps_initialized_sgprs(10 << 1), 11); - // 17 user SGPRs (s0..=s16) + prim_mask (s17): 18. - assert_eq!(ps_initialized_sgprs(17 << 1), 18); - // USER_SGPR_MSB (bit 28) extends user SGPRs to 32 + prim_mask: 33. - assert_eq!(ps_initialized_sgprs(1 << 28), 33); - // Scratch (bit 0), wave_cnt (bit 7), POPS collision wave id (bit 25), - // and intrawave collisions (bit 26) each add one SGPR. - assert_eq!(ps_initialized_sgprs((10 << 1) | 1), 12); - assert_eq!(ps_initialized_sgprs((10 << 1) | (1 << 7)), 12); - assert_eq!( - ps_initialized_sgprs((10 << 1) | 1 | (1 << 7) | (1 << 25) | (1 << 26)), - 15 - ); - // TRAP_PRESENT (bit 6), EXTRA_LDS_SIZE (8..=15), and EXCP_EN (16..=24) - // do not allocate general SGPRs. - assert_eq!( - ps_initialized_sgprs((10 << 1) | (1 << 6) | (0xFF << 8) | (0x1FF << 16)), - 11 - ); - let ps = StageIo::Ps { - inputs: vec![], - rsrc2: 17 << 1, - input_addr: 0, - db_shader_control: 0, - patches: vec![], - }; - assert_eq!(ps.initialized_sgprs(), Some(18)); - assert_eq!(StageIo::None.initialized_sgprs(), None); - } - #[test] fn reads_every_native_blob() { let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)])); @@ -1088,4 +1072,32 @@ mod tests { bad_record[at..at + 8].copy_from_slice(&u64::MAX.to_le_bytes()); assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&bad_record))])).is_err()); } + + #[test] + fn rejects_truncated_oversized_and_bad_checksum_xbch_streams() { + let plain = fssm(&[(HwStage::Vs, &VS_CODE)]); + let good = xbch(&plain); + assert_eq!(unpack(&good).unwrap(), plain); + + // Truncated zlib stream (drop last byte, update packed length). + let mut truncated = good[..good.len() - 1].to_vec(); + let new_packed = (truncated.len() - XBCH_HEADER) as u64; + truncated[8..16].copy_from_slice(&new_packed.to_le_bytes()); + assert!(unpack(&truncated).is_err()); + + // Stated unpacked size smaller than the inflated output. + let mut oversized = good.clone(); + oversized[16..24].copy_from_slice(&((plain.len() - 1) as u64).to_le_bytes()); + assert!(unpack(&oversized).is_err()); + + // Stated unpacked size larger than the inflated output. + let mut underfilled = good.clone(); + underfilled[16..24].copy_from_slice(&((plain.len() + 1) as u64).to_le_bytes()); + assert!(unpack(&underfilled).is_err()); + + // Corrupt Adler-32 trailer. + let mut bad_adler = good.clone(); + *bad_adler.last_mut().unwrap() ^= 1; + assert!(unpack(&bad_adler).is_err()); + } } diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 6b3d2e3..a27ae5e 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -12,15 +12,11 @@ //! memory address is traced through the SSA values back to those //! parameters, by data flow: copies, phis that agree, and additions. -use std::collections::HashMap; - use crate::ShaderError; use crate::gfx10::{Fields, NULL, Operand}; use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; use crate::native::{HwStage, RootParam, RootType}; -use crate::structure::{Atom, Bool, LaneExit, Meets, Structured}; - -mod uniform; +use crate::structure::{Bool, LaneExit, Meets, Structured}; /// An instruction: block and index in [`crate::ir::Block::insts`]. pub type Site = (usize, usize); @@ -42,51 +38,13 @@ pub struct Address { /// offset is then the byte offset in the code. pub const CODE: usize = usize::MAX; -/// [`Address::param`] of an address only known when the program runs: a -/// pointer it loads from memory, picks by control flow or computes (a -/// ray-tracing traversal follows the pointers in its BVH). The lowering -/// rebuilds the 64-bit address from the instruction's own operands and -/// reads title memory through the address map; `offset` and `dynamic` -/// are unused. -pub const GLOBAL: usize = usize::MAX - 1; - -/// Why an address has no root parameter, when the program computes it -/// from values a translation can reproduce: such an access reads title -/// memory at that address ([`GLOBAL`]). An address in an SGPR the -/// hardware fills (the console's spill table, say) has no host value, so -/// that case stays a refusal, as do the code-relative ones. -#[allow(dead_code)] -fn runtime_address(why: &str) -> bool { - matches!( - why, - "an address not from a root parameter" - | "an address from a phi" - | "an address loaded from memory" - | "an address with two computed terms" - | "an address from a root parameter that is no address" - ) -} - -/// The address of a memory access, or [`GLOBAL`] when [`runtime_address`] -/// says why it has none. -#[allow(dead_code)] -fn or_global(a: Result) -> Result { - match a { - Err(why) if runtime_address(why) => Ok(Address { - param: GLOBAL, - offset: 0, - dynamic: None, - }), - a => a, - } -} /// [`Address::param`] of title memory at an address no root parameter /// gives: one the code computes from root constants, reads out of a /// descriptor or loads from other memory (compute programs only: the /// ray-tracing structure builder and the programs that walk its /// structures). Offset and computed term are not used: lowering takes the /// 64-bit address from the instruction's operands. -pub const MEMORY: usize = usize::MAX - 2; +pub const MEMORY: usize = usize::MAX - 1; /// The reasons an address traces to no root parameter for which the /// address is then taken as it stands ([`MEMORY`]). @@ -206,8 +164,8 @@ pub enum BvhNodes { /// A buffer of the host: the descriptor is loaded from a table (it is /// among [`Resources::descriptors`]), and node pointers count from the /// buffer's start. Its flags are not known to the shader: boxes are - /// sorted and triangles return barycentrics, as every descriptor Grand - /// Theft Auto VI builds asks. + /// sorted and triangles return barycentrics, as every descriptor + /// the title builds asks. Resource, /// Title memory by address: the code makes the descriptor from numbers /// (the title: the whole address space, or one structure's address in @@ -277,7 +235,7 @@ pub fn track( let mut offset = Vec::new(); let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> { let source = t.descriptor(inst, op, b).map_err(fail)?; - // A descriptor the code keeps per lane ([`Tracer::lane_copies`]) + // A descriptor the code keeps per lane (`Tracer::lane_copies`) // is the same in every lane: its loop is lowered as it stands // and needs no proof. if !t.kept_per_lane(inst, op) { @@ -385,12 +343,12 @@ pub fn track( for (block, (accesses, mut reads)) in first_lane_at { reads.sort_unstable(); reads.dedup(); - let proof = - t.waterfall(block, &accesses, &reads) - .map_err(|what| ShaderError::Unsupported { - offset: t.inst((block, accesses[0])).machine.offset, - what, - })?; + let proof = t + .waterfall(block, &accesses, &reads) + .map_err(|what| ShaderError::Unsupported { + offset: t.inst((block, accesses[0])).machine.offset, + what, + })?; out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads); } @@ -417,7 +375,7 @@ pub fn track( } /// A dword after copy propagation. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Term { Const(u32), Value(Value), @@ -453,37 +411,10 @@ struct Tracer<'a> { meets: std::cell::RefCell, /// Reverse-postorder index per block. rpo: Vec, - /// Memo of [`Tracer::uniform`] per value. - uniform_memo: std::cell::RefCell>>, - /// Per value: whether a phi is uniform, settled on first use - /// ([`uniform`] module). - phi_ok: std::cell::RefCell>>, - regions: std::cell::OnceCell, /// The block of the access being traced ([`Self::live`]). at: std::cell::Cell>, } -/// VALU operations whose result is uniform when their operands are: the -/// address arithmetic a compiler moves into VGPRs and then reads back with -/// `v_readfirstlane_b32`. -const UNIFORM_VALU: &[&str] = &[ - "v_mov_b32", - "v_add_co_u32", - "v_add_nc_u32", - "v_add_co_ci_u32", - "v_sub_co_u32", - "v_sub_nc_u32", - "v_lshlrev_b32", - "v_lshlrev_b64", - "v_lshl_add_u32", - "v_add3_u32", - "v_ashrrev_i32", - "v_med3_i32", - "v_and_b32", - "v_or_b32", - "v_mul_lo_u32", -]; - /// What lanes are known to satisfy: each [`Bool`] where its flag is set, /// its negation where not. type Known = Vec<(Bool, bool)>; @@ -548,9 +479,6 @@ impl<'a> Tracer<'a> { read_first_lane: Default::default(), meets: Default::default(), rpo, - uniform_memo: std::cell::RefCell::new(vec![None; n]), - phi_ok: std::cell::RefCell::new(None), - regions: std::cell::OnceCell::new(), at: Default::default(), }; t.origin = t.propagate_copies(n)?; @@ -741,9 +669,6 @@ impl<'a> Tracer<'a> { dynamic: None, }; } - if let Some(src) = self.uniform_first_lane(v) { - return self.sum(self.vorigin(src)); - } // Paths that each add an index to a table in the code and meet before one // load: the join itself is the computed term. Lowering gives every // `s_getpc_b64` its own offset in the code as its value, so the join is the @@ -793,7 +718,7 @@ impl<'a> Tracer<'a> { /// For a join `v` whose every incoming value adds to an `s_getpc_b64` low /// dword: the first of those (one level of joins only). The paths may add /// to different ones: two tables in the code, one picked by control flow - /// (Grand Theft Auto VI's fog reconstruction reads its sample offsets from + /// (the title's fog reconstruction reads its sample offsets from /// one of two tables, by the sample's number; refused, the lit frame was /// multiplied by a fog transmittance nothing had written). fn code_join(&self, v: Value) -> Option { @@ -822,10 +747,9 @@ impl<'a> Tracer<'a> { /// [`Self::code_high`], at most `depth` additions deep. fn code_high_in(&self, t: Term, depth: u32) -> bool { let Term::Value(x) = t else { return false }; - if self - .def(x) - .is_some_and(|i| i.name() == "s_getpc_b64" && i.writes.get(1).is_some_and(|w| w.1 == x)) - { + if self.def(x).is_some_and(|i| { + i.name() == "s_getpc_b64" && i.writes.get(1).is_some_and(|w| w.1 == x) + }) { return true; } depth > 0 @@ -939,8 +863,6 @@ impl<'a> Tracer<'a> { && let Fields::Valu(f) = &inst.fields && f.abs == 0 && f.neg == 0 - && !f.clamp - && f.omod == 0 && f.sdwa.is_none() && f.dpp.is_none() && let Some(t) = f.src.first().and_then(|s| self.vterm(inst, s)) @@ -1013,12 +935,11 @@ impl<'a> Tracer<'a> { /// The address `lo` and `hi` hold, plus `extra` (an instruction's /// immediate and offset register). fn address(&self, lo: Term, hi: Term, extra: Sum) -> Result { - let lo = self.unlaned(lo); // The high half as the lanes that read through the address hold // it, where that is a constant or what a register held on entry // (the code clears a table address's high half inside a branch // and uses the address after the join). - let hi = match self.live(self.unlaned(hi)) { + let hi = match self.live(hi) { t @ Term::Const(_) => t, Term::Value(v) if self.inputs[v.0 as usize].is_some() => Term::Value(v), _ => hi, @@ -1037,11 +958,7 @@ impl<'a> Tracer<'a> { // A join of paths into tables in the code is the byte in the code // already: each path's `s_getpc_b64` counts as its own offset. let joined = s.dynamic.is_some_and(|d| self.code_join(d).is_some()); - let first = if joined { - 0 - } else { - pc.machine.offset as u32 + 4 - }; + let first = if joined { 0 } else { pc.machine.offset as u32 + 4 }; return Ok(Address { param: CODE, offset: first.wrapping_add(s.offset).wrapping_add(extra.offset), @@ -1088,9 +1005,7 @@ impl<'a> Tracer<'a> { /// `hi` adds something (with carry) to `high`: `s_addc_u32` or /// `v_add_co_ci_u32` with `high` as an operand. fn carried(&self, hi: Term, high: Value) -> bool { - let Term::Value(v) = self.unlaned(hi) else { - return false; - }; + let Term::Value(v) = hi else { return false }; if v == high { return true; } @@ -1156,9 +1071,6 @@ impl<'a> Tracer<'a> { return "an address relative to the program counter"; } match self.def(v).map(|i| i.name()) { - Some("v_readfirstlane_b32") => { - "an address read from the first lane of a per-lane value" - } Some(n) if n.starts_with("s_load_") => "an address loaded from memory", None => "an address from a phi", _ => "an address not from a root parameter", @@ -1297,7 +1209,7 @@ impl<'a> Tracer<'a> { /// other: the console compiler loads a descriptor (or clears an /// address's high half) inside a branch that skips code when no lane /// is left for it, and uses it after the join, where only lanes that - /// ran the branch are left (Grand Theft Auto VI's + /// ran the branch are left (the title's /// `CS_Alpha_Schedule`: the registers' values from before the branch, /// which the join also sees, are what a wave with no such lane holds). /// None at loop headers and without the lanes' paths. @@ -1565,65 +1477,6 @@ impl<'a> Tracer<'a> { inst.read(Reg::V(reg)) } - /// The VGPR a `v_readfirstlane_b32` writing `v` reads, when that value - /// is uniform: the first lane's is then every lane's. - fn uniform_first_lane(&self, v: Value) -> Option { - self.first_lane_source(v).filter(|&s| self.uniform(s)) - } - - /// `t`, with a first-lane read of a uniform value replaced by its source. - fn unlaned(&self, t: Term) -> Term { - match t { - Term::Value(v) => self - .uniform_first_lane(v) - .map_or(t, |src| self.vorigin(src)), - Term::Const(_) => t, - } - } - - /// Whether every lane holds the same value of `v`: built from scalars, - /// constants and first-lane reads, through [`UNIFORM_VALU`]. - fn uniform(&self, v: Value) -> bool { - let memo = self.uniform_memo.borrow()[v.0 as usize]; - if let Some(known) = memo { - return known; - } - let known = self.uniform_now(v); - self.uniform_memo.borrow_mut()[v.0 as usize] = Some(known); - known - } - - fn uniform_now(&self, v: Value) -> bool { - if let Some(reg) = self.inputs[v.0 as usize] { - return matches!(reg, Reg::S(_)); - } - if self.phis[v.0 as usize].is_some() { - return self.phi_uniform(v); - } - let Some(inst) = self.def(v) else { - return false; - }; - if matches!(inst.name(), "v_readfirstlane_b32" | "v_readlane_b32") { - return true; - } - let uniform_op = |op: &Operand| match *op { - Operand::Vector { reg, dwords } => { - (0..dwords).all(|k| inst.read(Reg::V(reg + k)).is_some_and(|x| self.uniform(x))) - } - Operand::Scalar { code, dwords } if code != NULL => { - (0..dwords).all(|k| inst.read(Reg::S(code + k)).is_some_and(|x| self.uniform(x))) - } - _ => true, - }; - match &inst.fields { - Fields::Sop { src, .. } => src.iter().all(uniform_op), - Fields::Valu(f) if UNIFORM_VALU.contains(&inst.name()) => { - f.src.iter().all(uniform_op) && self.valu_reads_uniform(inst, self.guarded(v)) - } - _ => false, - } - } - /// The `v_readfirstlane_b32` result the scalar load at `load` adds to /// its address as a table offset (the console's waterfall, /// `s_load_dwordx8 .., s[4:5], s20`): `track` proves the waterfall from @@ -1674,6 +1527,19 @@ impl<'a> Tracer<'a> { .collect() } + /// `t` through VGPR copies (of VGPRs or of scalars) and copies. + fn lane_term(&self, mut t: Term) -> Term { + for _ in 0..MAX_JOINS * 2 { + let Term::Value(v) = t else { break }; + let next = self.vorigin(v); + if next == t { + break; + } + t = next; + } + t + } + /// Whether `t` is a value each lane holds its own of (one in VGPRs). fn varies(&self, t: Term) -> bool { let Term::Value(v) = t else { return false }; @@ -1688,739 +1554,62 @@ impl<'a> Tracer<'a> { matches!(reg, Some(Reg::V(_))) } - /// `t` through VGPR copies and lane-preserving moves/extracts where - /// every lane in `known` sees the same result (including guarded writes - /// that provably rewrite what active lanes already held). - fn lane_value(&self, t: Term, known: &[(Bool, bool)]) -> Result { - self.lane_value_in(t, known, 0) - } - - fn lane_value_in( - &self, - mut t: Term, - known: &[(Bool, bool)], - depth: usize, - ) -> Result { + /// [`Self::lane_term`], where every lane in `known` runs each VGPR copy + /// it follows. + fn lane_value(&self, mut t: Term, known: &Known) -> Result { for _ in 0..MAX_JOINS * 2 { let Term::Value(v) = t else { break }; - if !self.varies(t) { - let next = self.origin(v); - if next == t { - break; - } - t = next; - continue; - } - let Some(site) = self.defs[v.0 as usize] else { + let next = self.vstep(v); + if next == t { break; - }; - if let Some((dst_reg, next)) = self.lane_copy(v) { - match self.runs(site, known) { - Ok(()) => { - if next == t { - break; - } - t = next; - } - Err(err) => { - t = self - .redundant_write(site, dst_reg, next, known, depth) - .ok_or(err)? - } - } - } else if let Some((dst_reg, _, _, _)) = self.lane_picked_with_reg(v) - && let Err(err) = self.runs(site, known) - { - // A guarded v_cndmask_b32 whose active lanes already hold the - // selected value is also a no-op across all lanes in `known`. - t = self - .redundant_write(site, dst_reg, Term::Value(v), known, depth) - .ok_or(err)?; - } else { - break; - } - } - Ok(t) - } - - /// When a guarded write to `dst_reg` at `site` writes `rhs` equal to the - /// prior value on every active lane in `known`, returns the prior value. - fn redundant_write( - &self, - site: Site, - dst_reg: Reg, - rhs: Term, - known: &[(Bool, bool)], - depth: usize, - ) -> Option { - if depth >= MAX_JOINS { - return None; - } - let old = self.inst(site).read(dst_reg)?; - let lanes = self.lanes?; - let guard = lanes.guards[site.0][site.1]?; - let mut active = known.to_vec(); - active.extend([(lanes.reach[site.0], true), (guard, true)]); - self.lane_value_equals(Term::Value(old), rhs, &active, depth + 1) - .then_some(Term::Value(old)) - } - - /// A single lane-preserving VGPR copy, identity ALU operation, or - /// 32-bit word extract writing `v`: its destination register and the - /// value written when active. - fn lane_copy(&self, v: Value) -> Option<(Reg, Term)> { - let inst = self.def(v)?; - let Fields::Valu(f) = &inst.fields else { - return None; - }; - if f.abs != 0 || f.neg != 0 || f.clamp || f.omod != 0 || f.dpp.is_some() { - return None; - } - let name = inst.name(); - if name == "v_mov_b32" { - let Some(Operand::Vector { reg, .. }) = f.dst else { - return None; - }; - if inst.write(Reg::V(reg)) != Some(v) { - return None; - } - if !f - .sdwa - .is_none_or(|s| s.dst_sel == 6 && s.src_sel[0] == 6 && s.sext & 1 == 0) - { - return None; - } - return Some((Reg::V(reg), self.raw(inst, f.src.first()?)?)); - } - if f.sdwa.is_some() { - return None; - } - if name == "v_swap_b32" { - let (Some(Operand::Vector { reg: dreg, .. }), Some(&Operand::Vector { reg: sreg, .. })) = - (f.dst, f.src.first()) - else { - return None; - }; - if inst.write(Reg::V(dreg)) == Some(v) { - return Some((Reg::V(dreg), Term::Value(inst.read(Reg::V(sreg))?))); - } - if inst.write(Reg::V(sreg)) == Some(v) { - return Some((Reg::V(sreg), Term::Value(inst.read(Reg::V(dreg))?))); - } - return None; - } - let Some(Operand::Vector { reg: dreg, dwords }) = f.dst else { - return None; - }; - if dwords == 2 && matches!(name, "v_lshrrev_b64" | "v_ashrrev_i64" | "v_lshlrev_b64") { - let [sh_op, src_op] = &f.src[..] else { - return None; - }; - let Term::Const(sh) = self.raw(inst, sh_op)? else { - return None; - }; - let words = self.raw64(inst, src_op)?; - let sh = sh & 63; - let k = inst - .writes - .iter() - .filter(|w| matches!(w.0, Reg::V(_))) - .position(|w| w.1 == v)?; - let reg = Reg::V(dreg + k as u8); - return match (name, sh, k) { - (_, 0, 0) => Some((reg, words[0])), - (_, 0, 1) => Some((reg, words[1])), - ("v_lshrrev_b64" | "v_ashrrev_i64", 32, 0) => Some((reg, words[1])), - ("v_lshrrev_b64", 32, 1) => Some((reg, Term::Const(0))), - ("v_lshlrev_b64", 32, 0) => Some((reg, Term::Const(0))), - ("v_lshlrev_b64", 32, 1) => Some((reg, words[0])), - _ => None, - }; - } - if inst.write(Reg::V(dreg)) != Some(v) { - return None; - } - let dst_reg = Reg::V(dreg); - let op = |k: usize| self.raw(inst, f.src.get(k)?); - let term = match name { - "v_or_b32" => match (op(0)?, op(1)?) { - (a, Term::Const(0)) | (Term::Const(0), a) => Some(a), - (a, b) if a == b => Some(a), - _ => None, - }, - "v_and_b32" => match (op(0)?, op(1)?) { - (a, Term::Const(u32::MAX)) | (Term::Const(u32::MAX), a) => Some(a), - (a, b) if a == b => Some(a), - _ => None, - }, - "v_xor_b32" => match (op(0)?, op(1)?) { - (a, Term::Const(0)) | (Term::Const(0), a) => Some(a), - _ => None, - }, - "v_add_nc_u32" | "v_add_co_u32" => match (op(0)?, op(1)?) { - (a, Term::Const(0)) | (Term::Const(0), a) => Some(a), - _ => None, - }, - "v_sub_nc_u32" | "v_sub_co_u32" => match (op(0)?, op(1)?) { - (a, Term::Const(0)) => Some(a), - _ => None, - }, - "v_subrev_nc_u32" | "v_subrev_co_u32" => match (op(0)?, op(1)?) { - (Term::Const(0), a) => Some(a), - _ => None, - }, - "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => match (op(0)?, op(1)?) { - (Term::Const(sh), a) if sh & 31 == 0 => Some(a), - _ => None, - }, - "v_mul_lo_u32" => match (op(0)?, op(1)?) { - (a, Term::Const(1)) | (Term::Const(1), a) => Some(a), - _ => None, - }, - "v_min_u32" => match (op(0)?, op(1)?) { - (a, Term::Const(u32::MAX)) | (Term::Const(u32::MAX), a) => Some(a), - (a, b) if a == b => Some(a), - _ => None, - }, - "v_max_u32" => match (op(0)?, op(1)?) { - (a, Term::Const(0)) | (Term::Const(0), a) => Some(a), - (a, b) if a == b => Some(a), - _ => None, - }, - "v_min_i32" | "v_max_i32" => match (op(0)?, op(1)?) { - (a, b) if a == b => Some(a), - _ => None, - }, - "v_bfi_b32" => match (op(0)?, op(1)?, op(2)?) { - (Term::Const(u32::MAX), a, _) | (Term::Const(0), _, a) => Some(a), - (_, a, b) if a == b => Some(a), - _ => None, - }, - "v_perm_b32" => match (op(0)?, op(1)?, op(2)?) { - (_, src1, Term::Const(0x0302_0100)) => Some(src1), - (src0, _, Term::Const(0x0706_0504)) => Some(src0), - _ => None, - }, - "v_alignbit_b32" => match (op(1)?, op(2)?) { - (src1, Term::Const(sh)) if sh & 31 == 0 => Some(src1), - _ => None, - }, - "v_alignbyte_b32" => match (op(1)?, op(2)?) { - (src1, Term::Const(sh)) if sh & 3 == 0 => Some(src1), - _ => None, - }, - "v_cndmask_b32" => { - let (clear, set, mask) = (op(0)?, op(1)?, f.src.get(2)?); - match *mask { - Operand::Scalar { code: NULL, .. } - | Operand::Const(128) - | Operand::Literal(0) => Some(clear), - Operand::Const(193) => Some(set), - Operand::Literal(u32::MAX) if !self.p.wave64 => Some(set), - _ if clear == set => Some(clear), - _ => None, - } - } - _ => None, - }?; - Some((dst_reg, term)) - } - - /// Resolves a 64-bit VALU operand to its `[low, high]` dwords. - fn raw64(&self, inst: &Inst, op: &Operand) -> Option<[Term; 2]> { - match *op { - Operand::Vector { reg, .. } => Some([ - Term::Value(inst.read(Reg::V(reg))?), - Term::Value(inst.read(Reg::V(reg + 1))?), - ]), - Operand::Scalar { code: NULL, .. } => Some([Term::Const(0), Term::Const(0)]), - Operand::Scalar { code, .. } => Some([ - self.origin(inst.read(Reg::S(code))?), - self.origin(inst.read(Reg::S(code + 1))?), - ]), - Operand::Const(c @ 128..=208) => { - let low = inline(c)?; - Some([Term::Const(low), Term::Const(((low as i32) >> 31) as u32)]) - } - Operand::Literal(x) => Some([Term::Const(x), Term::Const(0)]), - _ => None, - } - } - - /// A VALU operand as `inst` reads it: a VGPR's value itself, other - /// operands' origins. - fn raw(&self, inst: &Inst, op: &Operand) -> Option { - match *op { - Operand::Vector { reg, .. } => Some(Term::Value(inst.read(Reg::V(reg))?)), - op => self.term(inst, &op), - } - } - - /// Proves that `a` and `b` evaluate to the same 32-bit word in every lane - /// satisfying `known`. - fn lane_value_equals(&self, a: Term, b: Term, known: &[(Bool, bool)], depth: usize) -> bool { - if !self.feasible(known) { - return true; - } - if depth > MAX_JOINS { - return false; - } - let Ok(a) = self.lane_value_in(a, known, depth) else { - return false; - }; - let Ok(b) = self.lane_value_in(b, known, depth) else { - return false; - }; - if a == b { - return true; - } - if depth == MAX_JOINS { - return false; - } - if let Some(branches) = self.split_term(a, known) { - let mut next_known = known.to_vec(); - return branches.into_iter().all(|(ext, arg)| { - let n = next_known.len(); - next_known.extend(ext); - let ok = self.lane_value_equals(arg, b, &next_known, depth + 1); - next_known.truncate(n); - ok - }); - } - if let Some(branches) = self.split_term(b, known) { - let mut next_known = known.to_vec(); - return branches.into_iter().all(|(ext, arg)| { - let n = next_known.len(); - next_known.extend(ext); - let ok = self.lane_value_equals(a, arg, &next_known, depth + 1); - next_known.truncate(n); - ok - }); - } - false - } - - /// Splits a forward phi or select `t` into `(edge_conditions, branch_term)` - /// cases under `known`. - fn split_term(&self, t: Term, known: &[(Bool, bool)]) -> Option> { - let Term::Value(v) = t else { return None }; - if let Some((block, phi_idx)) = self.phis[v.0 as usize] { - let preds = &self.p.blocks[block].preds; - if preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) { - return None; - } - let lanes = self.lanes?; - let args = &self.p.blocks[block].phis[phi_idx].args; - return Some( - preds - .iter() - .enumerate() - .map(|(j, &q)| { - let mut ext = vec![(lanes.reach[q], true)]; - if let LaneExit::Branch { - when, - taken, - not_taken, - } = lanes.exits[q] - && taken != not_taken - { - ext.push((when, taken == block)); - } - (ext, Term::Value(args[j])) - }) - .collect(), - ); - } - if let Some((_, mask, set_val, clear_val)) = self.lane_picked_with_reg(v) { - let site = self.defs[v.0 as usize]?; - self.runs(site, known).ok()?; - let bit = self.lanes?.masks.get(&mask).copied()?; - return Some(vec![ - (vec![(bit, true)], set_val), - (vec![(bit, false)], clear_val), - ]); - } - if let Some((scc, set_val, clear_val)) = self.picked(v) { - if let Some(lanes) = self.lanes - && let Some(ub) = lanes.bools.var_bool(Atom::Uniform(scc)) - { - return Some(vec![ - (vec![(ub, true)], set_val), - (vec![(ub, false)], clear_val), - ]); - } - return Some(vec![(vec![], set_val), (vec![], clear_val)]); - } - None - } - - /// Whether some lane can satisfy all conditions in `all`, taking into - /// account equivalent/opposite `v_cmp` lane atoms and 1D integer bounds. - fn feasible(&self, all: &[(Bool, bool)]) -> bool { - let Some(lanes) = self.lanes else { - return true; - }; - if !lanes.bools.meet(all) { - return false; - } - let mut lane_atoms = Vec::new(); - for &(b, _) in all { - for atom in lanes.bools.support(b) { - if matches!(atom, Atom::Lane(_)) && !lane_atoms.contains(&atom) { - lane_atoms.push(atom); - } - } - } - if lane_atoms.len() < 2 { - return true; - } - let mut groups: HashMap = HashMap::new(); - let mut equiv = Vec::new(); - for &atom in &lane_atoms { - let Atom::Lane(v) = atom else { continue }; - if let Some((key, inv)) = self.canon_cmp(v) { - let next_id = groups.len(); - let group = *groups.entry(key).or_insert(next_id); - equiv.push((atom, group, inv)); - } - } - if equiv.is_empty() { - return true; - } - let groups_len = groups.len(); - lanes - .bools - .meet_with_facts(all, &equiv, groups_len, |assigned| { - self.cmp_leaf_ok(assigned) - }) - } - - fn feasible_with(&self, known: &[(Bool, bool)], extra: &[(Bool, bool)]) -> bool { - let mut conds = Vec::with_capacity(known.len() + extra.len()); - conds.extend_from_slice(known); - conds.extend_from_slice(extra); - self.feasible(&conds) - } - - /// Whether two mask values evaluate to the same boolean on every lane in - /// `known` (and both are tracked in `lanes.masks` when `lanes` is present). - fn same_mask(&self, a: Value, b: Value, known: &[(Bool, bool)]) -> bool { - if a == b { - return true; - } - let Some(lanes) = self.lanes else { - return false; - }; - let (Some(&ma), Some(&mb)) = (lanes.masks.get(&a), lanes.masks.get(&b)) else { - return false; - }; - ma == mb - || (!self.feasible_with(known, &[(ma, true), (mb, false)]) - && !self.feasible_with(known, &[(ma, false), (mb, true)])) - } - - /// Canonicalizes a pure `v_cmp_*` / `v_cmpx_*` instruction defining `v` - /// into `(canonical_key, inverted)` so equivalent or negated compares - /// share the same key. - fn canon_cmp(&self, v: Value) -> Option<(CanonKey, bool)> { - let inst = self.def(v)?; - let Fields::Valu(f) = &inst.fields else { - return None; - }; - if f.dpp.is_some() || f.clamp || f.omod != 0 { - return None; - } - let rest = inst - .name() - .strip_prefix("v_cmp_") - .or_else(|| inst.name().strip_prefix("v_cmpx_"))?; - let (op, ty_str) = rest.rsplit_once('_')?; - let ty = match ty_str { - "u16" => CmpType::U16, - "i16" => CmpType::I16, - "f16" => CmpType::F16, - "u32" => CmpType::U32, - "i32" => CmpType::I32, - "f32" => CmpType::F32, - "u64" => CmpType::U64, - "i64" => CmpType::I64, - "f64" => CmpType::F64, - _ => return None, - }; - let a = self.cmp_operand(inst, f, 0, ty)?; - let b = self.cmp_operand(inst, f, 1, ty)?; - let ordered = |x: CmpOperand, y: CmpOperand| if x <= y { (x, y) } else { (y, x) }; - let (pred, inv) = match ty { - CmpType::U16 - | CmpType::I16 - | CmpType::U32 - | CmpType::I32 - | CmpType::U64 - | CmpType::I64 => match op { - "f" => (CanonPred::Const(false), false), - "t" => (CanonPred::Const(true), false), - "lt" => (CanonPred::IntLt(a, b), false), - "ge" => (CanonPred::IntLt(a, b), true), - "gt" => (CanonPred::IntLt(b, a), false), - "le" => (CanonPred::IntLt(b, a), true), - "eq" => { - let (lo, hi) = ordered(a, b); - (CanonPred::IntEq(lo, hi), false) - } - "ne" | "lg" => { - let (lo, hi) = ordered(a, b); - (CanonPred::IntEq(lo, hi), true) - } - _ => return None, - }, - CmpType::F16 | CmpType::F32 | CmpType::F64 => match op { - "f" => (CanonPred::Const(false), false), - "tru" => (CanonPred::Const(true), false), - "lt" => (CanonPred::FloatLt(a, b), false), - "nlt" => (CanonPred::FloatLt(a, b), true), - "gt" => (CanonPred::FloatLt(b, a), false), - "ngt" => (CanonPred::FloatLt(b, a), true), - "le" => (CanonPred::FloatLe(a, b), false), - "nle" => (CanonPred::FloatLe(a, b), true), - "ge" => (CanonPred::FloatLe(b, a), false), - "nge" => (CanonPred::FloatLe(b, a), true), - "eq" => { - let (lo, hi) = ordered(a, b); - (CanonPred::FloatEq(lo, hi), false) - } - "neq" => { - let (lo, hi) = ordered(a, b); - (CanonPred::FloatEq(lo, hi), true) - } - "lg" => { - let (lo, hi) = ordered(a, b); - (CanonPred::FloatLg(lo, hi), false) - } - "nlg" => { - let (lo, hi) = ordered(a, b); - (CanonPred::FloatLg(lo, hi), true) - } - "o" => { - let (lo, hi) = ordered(a, b); - (CanonPred::FloatOrd(lo, hi), false) - } - "u" => { - let (lo, hi) = ordered(a, b); - (CanonPred::FloatOrd(lo, hi), true) - } - "class" => (CanonPred::FloatClass(a, b), false), - _ => return None, - }, - }; - Some((CanonKey { ty, pred }, inv)) - } - - fn cmp_operand( - &self, - inst: &Inst, - f: &crate::gfx10::Valu, - k: usize, - ty: CmpType, - ) -> Option { - let op = *f.src.get(k)?; - let words = match ty { - CmpType::U64 | CmpType::I64 | CmpType::F64 => match op { - Operand::Vector { reg, .. } => [ - self.lane_unconditional(inst.read(Reg::V(reg))?), - self.lane_unconditional(inst.read(Reg::V(reg + 1))?), - ], - Operand::Scalar { code: NULL, .. } => [Term::Const(0), Term::Const(0)], - Operand::Scalar { code, .. } => [ - self.origin(inst.read(Reg::S(code))?), - self.origin(inst.read(Reg::S(code + 1))?), - ], - Operand::Const(c @ 128..=208) => { - let low = inline(c)?; - [Term::Const(low), Term::Const(((low as i32) >> 31) as u32)] - } - Operand::Literal(x) => [Term::Const(x), Term::Const(0)], - _ => return None, - }, - _ => { - let w = match op { - Operand::Vector { reg, .. } => self.lane_unconditional(inst.read(Reg::V(reg))?), - Operand::Const(c) if ty == CmpType::F16 && c >= 240 => return None, - _ => self.term(inst, &op)?, - }; - [w, Term::Const(0)] } - }; - let is16 = matches!(ty, CmpType::U16 | CmpType::I16 | CmpType::F16); - Some(CmpOperand { - words, - abs: (f.abs >> k) & 1 != 0, - neg: (f.neg >> k) & 1 != 0, - opsel: is16 && ((f.opsel >> k) & 1 != 0), - sdwa: f.sdwa.map(|s| (s.src_sel[k], (s.sext >> k) & 1 != 0)), - }) - } - - /// Follows unconditional lane-preserving copies (those with no guard) - /// from `v`. - fn lane_unconditional(&self, mut v: Value) -> Term { - for _ in 0..MAX_JOINS * 2 { - let Some(site) = self.defs[v.0 as usize] else { - return Term::Value(v); - }; - if self - .lanes - .is_some_and(|l| l.guards[site.0][site.1].is_some()) + if self.varies(t) + && let Some(site) = self.defs[v.0 as usize] { - return Term::Value(v); - } - let Some((_, next)) = self.lane_copy(v) else { - return Term::Value(v); - }; - match next { - Term::Value(u) if u != v => v = u, - other => return other, + self.runs(site, known)?; } + t = next; } - Term::Value(v) + Ok(t) } - /// Checks whether a leaf assignment of `Atom::Lane` compares is consistent - /// with 1D integer constant bounds (e.g., `(x < 8) && !(x < 16)` is false). - fn cmp_leaf_ok(&self, assigned: &[(Atom, bool)]) -> bool { - struct Bounds { - lo: i128, - hi: i128, - neq: Vec, - } - fn entry_for( - map: &mut HashMap<(CmpType, CmpOperand), Bounds>, - ty: CmpType, - op: CmpOperand, - ) -> &mut Bounds { - let (min, max) = match ty { - CmpType::U16 => (0i128, i128::from(u16::MAX)), - CmpType::I16 => (i128::from(i16::MIN), i128::from(i16::MAX)), - CmpType::U32 => (0i128, i128::from(u32::MAX)), - CmpType::I32 => (i128::from(i32::MIN), i128::from(i32::MAX)), - CmpType::U64 => (0i128, i128::from(u64::MAX)), - CmpType::I64 => (i128::from(i64::MIN), i128::from(i64::MAX)), - _ => (0, 0), - }; - map.entry((ty, op)).or_insert(Bounds { - lo: min, - hi: max, - neq: Vec::new(), - }) + /// One copy of [`Self::vorigin`]: what the `v_mov_b32` writing `v` + /// reads, or `v`'s origin. + fn vstep(&self, v: Value) -> Term { + if let Some(inst) = self.def(v) + && inst.name() == "v_mov_b32" + && let Fields::Valu(f) = &inst.fields + && f.abs == 0 + && f.neg == 0 + && f.sdwa.is_none() + && f.dpp.is_none() + && let Some(t) = f.src.first().and_then(|s| self.raw(inst, s)) + { + return t; } - let mut bounds: HashMap<(CmpType, CmpOperand), Bounds> = HashMap::new(); - let int_const = |ty: CmpType, op: CmpOperand| -> Option { - if op.abs || op.neg || op.opsel || op.sdwa.is_some() { - return None; - } - let (Term::Const(w0), Term::Const(w1)) = (op.words[0], op.words[1]) else { - return None; - }; - Some(match ty { - CmpType::U16 => i128::from(w0 as u16), - CmpType::I16 => i128::from(w0 as u16 as i16), - CmpType::U32 => i128::from(w0), - CmpType::I32 => i128::from(w0 as i32), - CmpType::U64 => i128::from(u64::from(w0) | (u64::from(w1) << 32)), - CmpType::I64 => i128::from((u64::from(w0) | (u64::from(w1) << 32)) as i64), - _ => return None, - }) - }; - for &(atom, truth) in assigned { - let Atom::Lane(v) = atom else { continue }; - let Some((CanonKey { ty, pred }, inv)) = self.canon_cmp(v) else { - continue; - }; - let holds = truth ^ inv; - match pred { - CanonPred::Const(c) => { - if c != holds { - return false; - } - } - CanonPred::IntLt(a, b) => { - if a == b { - if holds { - return false; - } - continue; - } - if let (Some(ka), Some(kb)) = (int_const(ty, a), int_const(ty, b)) { - if (ka < kb) != holds { - return false; - } - continue; - } - if let Some(k) = int_const(ty, b) { - let e = entry_for(&mut bounds, ty, a); - if holds { - e.hi = e.hi.min(k - 1); - } else { - e.lo = e.lo.max(k); - } - } else if let Some(k) = int_const(ty, a) { - let e = entry_for(&mut bounds, ty, b); - if holds { - e.lo = e.lo.max(k + 1); - } else { - e.hi = e.hi.min(k); - } - } - } - CanonPred::IntEq(a, b) => { - if a == b { - if !holds { - return false; - } - continue; - } - if let (Some(ka), Some(kb)) = (int_const(ty, a), int_const(ty, b)) { - if (ka == kb) != holds { - return false; - } - continue; - } - if let Some(k) = int_const(ty, b) { - let e = entry_for(&mut bounds, ty, a); - if holds { - e.lo = e.lo.max(k); - e.hi = e.hi.min(k); - } else { - e.neq.push(k); - } - } else if let Some(k) = int_const(ty, a) { - let e = entry_for(&mut bounds, ty, b); - if holds { - e.lo = e.lo.max(k); - e.hi = e.hi.min(k); - } else { - e.neq.push(k); - } - } - } - _ => {} - } + self.origin(v) + } + + /// A VALU operand as `inst` reads it: a VGPR's value itself, other + /// operands' origins. + fn raw(&self, inst: &Inst, op: &Operand) -> Option { + match *op { + Operand::Vector { reg, .. } => Some(Term::Value(inst.read(Reg::V(reg))?)), + op => self.term(inst, &op), } - bounds - .values() - .all(|b| b.lo <= b.hi && (b.lo != b.hi || !b.neq.contains(&b.lo))) } /// Fails unless every lane in `known` that reaches the vector /// instruction at `site` runs it: one with its EXEC bit clear there /// keeps what the registers held before. - fn runs(&self, site: Site, known: &[(Bool, bool)]) -> Result<(), &'static str> { + fn runs(&self, site: Site, known: &Known) -> Result<(), &'static str> { let Some(lanes) = self.lanes else { return Ok(()); }; let Some(&Some(guard)) = lanes.guards.get(site.0).and_then(|g| g.get(site.1)) else { return Ok(()); }; - let mut skips = known.to_vec(); + let mut skips = known.clone(); skips.extend([(lanes.reach[site.0], true), (guard, false)]); if self.meet(lanes, &skips) { return Err("a per-lane descriptor written where some lanes may keep the old one"); @@ -2546,11 +1735,7 @@ impl<'a> Tracer<'a> { let Some(mask) = picks.iter().flatten().map(|p| p.0).next() else { return Ok(None); }; - if picks - .iter() - .flatten() - .any(|p| !self.same_mask(p.0, mask, known)) - { + if picks.iter().flatten().any(|p| p.0 != mask) { return Err("a descriptor chosen per lane by several masks"); } for (w, p) in words.iter().zip(&picks) { @@ -2560,6 +1745,11 @@ impl<'a> Tracer<'a> { self.runs(site, known)?; } } + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(usize::MAX); + // Each side holds where the lane's bit of the mask is set, or clear. let bit = self.lanes.and_then(|l| l.masks.get(&mask).copied()); let side = |set: bool| -> Vec { words @@ -2577,18 +1767,6 @@ impl<'a> Tracer<'a> { }) .collect() }; - if let Some(b) = bit { - let t_ok = self.feasible_with(known, &[(b, true)]); - let f_ok = self.feasible_with(known, &[(b, false)]); - if t_ok != f_ok { - return self.per_lane(&side(t_ok), joins, known).map(Some); - } - } - if joins.len() >= MAX_JOINS { - return Err("a descriptor joined too often"); - } - joins.push(usize::MAX); - // Each side holds where the lane's bit of the mask is set, or clear. let args = [true, false] .into_iter() .map(|set| { @@ -2607,11 +1785,6 @@ impl<'a> Tracer<'a> { /// lane mask it reads, and the dword it is where the lane's bit is set /// (src1), then clear (src0). fn lane_picked(&self, v: Value) -> Option<(Value, Term, Term)> { - let (_, mask, set, clear) = self.lane_picked_with_reg(v)?; - Some((mask, set, clear)) - } - - fn lane_picked_with_reg(&self, v: Value) -> Option<(Reg, Value, Term, Term)> { let inst = self.def(v)?; let Fields::Valu(f) = &inst.fields else { return None; @@ -2634,12 +1807,7 @@ impl<'a> Tracer<'a> { return None; }; let mask = inst.read(Reg::S(code))?; - Some(( - Reg::V(reg), - mask, - self.raw(inst, &set)?, - self.raw(inst, &clear)?, - )) + Some((mask, self.raw(inst, &set)?, self.raw(inst, &clear)?)) } /// Per-lane words that phis of one block join, as an if/else on a @@ -2807,7 +1975,6 @@ impl<'a> Tracer<'a> { return Err(SELECT); } let reach = (lanes.reach[b], true); - let loop_known = [reach, (remaining, true)]; let meet = |conditions: &[(Bool, bool)]| self.meet(lanes, conditions); let mut out = Waterfall::default(); let mut required = vec![(remaining, true)]; @@ -2846,16 +2013,8 @@ impl<'a> Tracer<'a> { let (_, read) = self.defs[x.0 as usize]?; let same = reads.contains(&x) && read < i - && match ( - self.lane_value( - Term::Value(self.first_lane_source(x)?), - &loop_known, - ), - self.lane_value(Term::Value(lane), &loop_known), - ) { - (Ok(lhs), Ok(rhs)) => lhs == rhs, - _ => false, - }; + && self.lane_term(Term::Value(self.first_lane_source(x)?)) + == self.lane_term(Term::Value(lane)); same.then_some(x) }) .collect() @@ -2871,8 +2030,7 @@ impl<'a> Tracer<'a> { } else { continue; }; - let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) - else { + let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) else { continue; }; if meet(&[reach, (selected, true), (matched, false)]) { @@ -3087,47 +2245,6 @@ impl<'a> Tracer<'a> { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -enum CmpType { - U16, - I16, - F16, - U32, - I32, - F32, - U64, - I64, - F64, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -struct CmpOperand { - words: [Term; 2], - abs: bool, - neg: bool, - opsel: bool, - sdwa: Option<(u8, bool)>, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -enum CanonPred { - Const(bool), - IntLt(CmpOperand, CmpOperand), - IntEq(CmpOperand, CmpOperand), - FloatLt(CmpOperand, CmpOperand), - FloatLe(CmpOperand, CmpOperand), - FloatEq(CmpOperand, CmpOperand), - FloatLg(CmpOperand, CmpOperand), - FloatOrd(CmpOperand, CmpOperand), - FloatClass(CmpOperand, CmpOperand), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -struct CanonKey { - ty: CmpType, - pred: CanonPred, -} - #[derive(Clone, Copy, PartialEq, Eq)] enum Moved { Const(u32), @@ -3507,10 +2624,7 @@ pub(crate) mod tests { assert_eq!(r.scalar.len(), 1); let a = r.scalar[0].1; assert_eq!((a.param, a.offset), (CODE, 0)); - assert!( - a.dynamic.is_some(), - "the join is the computed term, the byte in the code" - ); + assert!(a.dynamic.is_some(), "the join is the computed term, the byte in the code"); } /// An address into a table in the code computed per lane and taken from @@ -3698,126 +2812,6 @@ pub(crate) mod tests { ); } - /// A scalar load of a table in the code, at an address a VGPR sum builds - /// from `s_getpc_b64` and a uniform index, read back to SGPRs with - /// `v_readfirstlane_b32` (the console compiler's form). Assembled with - /// llvm-mc for gfx1030, wave32. - const CODE_TABLE_FIRST_LANE: &[u32] = &[ - 0xBE80_1F00, // s_getpc_b64 s[0:1] - 0x8000_FF00, - 0x0000_0DDC, // s_add_u32 s0, s0, 0xddc - 0x8201_8001, // s_addc_u32 s1, s1, 0 - 0x7E00_0283, // v_mov_b32 v0, 3 - 0x3402_0082, // v_lshlrev_b32 v1, 2, v0 - 0xD70F_6A01, - 0x0000_0101, // v_add_co_u32 v1, vcc_lo, v1, s0 - 0xD528_6A02, - 0x01A9_0001, // v_add_co_ci_u32 v2, vcc_lo, s1, 0, vcc_lo - 0x7E04_0501, // v_readfirstlane_b32 s2, v1 - 0x7E06_0502, // v_readfirstlane_b32 s3, v2 - 0xF400_0181, - 0xFA00_0000, // s_load_dword s6, s[2:3], null - S_ENDPGM, - ]; - - #[test] - fn a_first_lane_read_of_a_uniform_code_table_address_is_traced() { - let r = track_words(CODE_TABLE_FIRST_LANE, &[], HwStage::Cs); - let (_, a) = r - .scalar - .iter() - .find(|s| s.1.param == CODE) - .expect("the code table load is traced"); - // s_getpc_b64 is the first instruction: its next one is at 4. - assert_eq!(a.offset, 4 + 0xDDC); - assert!(a.dynamic.is_some(), "the index stays a computed term"); - } - - #[test] - fn a_first_lane_read_of_a_per_lane_code_table_address_is_traced() { - // Same, but the index is lane 0's own input (v0 is never set): - // lane 0's address, a table in the code at a computed offset. - let words = [ - 0xBE80_1F00, // s_getpc_b64 s[0:1] - 0x8000_FF00, - 0x0000_0DDC, // s_add_u32 s0, s0, 0xddc - 0x8201_8001, // s_addc_u32 s1, s1, 0 - 0x3402_0082, // v_lshlrev_b32 v1, 2, v0 - 0xD70F_6A01, - 0x0000_0101, // v_add_co_u32 v1, vcc_lo, v1, s0 - 0xD528_6A02, - 0x01A9_0001, // v_add_co_ci_u32 v2, vcc_lo, s1, 0, vcc_lo - 0x7E04_0501, // v_readfirstlane_b32 s2, v1 - 0x7E06_0502, // v_readfirstlane_b32 s3, v2 - 0xF400_0181, - 0xFA00_0000, // s_load_dword s6, s[2:3], null - S_ENDPGM, - ]; - let r = track_words(&words, &[], HwStage::Cs); - let (_, a) = r - .scalar - .iter() - .find(|s| s.1.param == CODE) - .expect("the code table load is traced"); - assert_eq!(a.offset, 4 + 0xDDC); - assert!(a.dynamic.is_some(), "the index stays a computed term"); - } - - /// A table in the code read in a loop whose counter (v7) the exit test - /// compares with `limit`: the console compiler's form for a lookup table - /// walked at a uniform index. Assembled with llvm-mc for gfx1030, wave32. - fn code_table_loop(compare: u32) -> Vec { - vec![ - 0xBE80_1F00, // s_getpc_b64 s[0:1] - 0x8000_FF00, - 0x0000_0DDC, // s_add_u32 s0, s0, 0xddc - 0x8201_8001, // s_addc_u32 s1, s1, 0 - 0x7E0E_0280, // v_mov_b32 v7, 0 - 0x3402_0E82, // loop: v_lshlrev_b32 v1, 2, v7 - 0xD70F_6A01, - 0x0000_0101, // v_add_co_u32 v1, vcc_lo, v1, s0 - 0xD528_6A02, - 0x01A9_0001, // v_add_co_ci_u32 v2, vcc_lo, s1, 0, vcc_lo - 0x7E04_0501, // v_readfirstlane_b32 s2, v1 - 0x7E06_0502, // v_readfirstlane_b32 s3, v2 - 0xF400_0181, - 0xFA00_0000, // s_load_dword s6, s[2:3], null - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0x4A0E_0E81, // v_add_nc_u32 v7, 1, v7 - compare, - 0xBF87_FFF3, // s_cbranch_vccnz loop - S_ENDPGM, - ] - } - - #[test] - fn a_loop_counter_with_a_uniform_exit_indexes_a_code_table() { - // v_cmp_gt_i32 vcc_lo, 5, v7 - let r = track_words(&code_table_loop(0x7D08_0E85), &[], HwStage::Cs); - let (_, a) = r - .scalar - .iter() - .find(|s| s.1.param == CODE) - .expect("the code table load is traced"); - assert_eq!(a.offset, 4 + 0xDDC); - assert!(a.dynamic.is_some(), "the counter stays a computed term"); - } - - #[test] - fn a_loop_counter_with_a_per_lane_exit_is_traced() { - // v_cmp_gt_u32 vcc_lo, v0, v7: lanes leave at their own count. - // The first lane's address is still a code table at a computed - // offset: traced the same, the per-lane count stays a computed term. - let r = track_words(&code_table_loop(0x7D88_0F00), &[], HwStage::Cs); - let (_, a) = r - .scalar - .iter() - .find(|s| s.1.param == CODE) - .expect("the code table load is traced"); - assert_eq!(a.offset, 4 + 0xDDC); - assert!(a.dynamic.is_some(), "the counter stays a computed term"); - } - /// A waterfall loop over an image descriptor each lane loads from the /// table at s0 (wave32, assembled with llvm-mc for gfx1030): lane i /// reads entry i with two `global_load_dwordx4`, the loop reads the @@ -4068,7 +3062,7 @@ pub(crate) mod tests { 0xBF81_0000, // s_endpgm ]; - /// The console compiler's waterfall (Grand Theft Auto VI's ray-tracing + /// The console compiler's waterfall (the title's ray-tracing /// resolve and others): each lane holds its entry's byte offset in the /// table at s0 (v7 = (lane & 1) * 32); the loop reads the first active /// lane's offset, narrows EXEC to the lanes with the same one @@ -4851,477 +3845,4 @@ pub(crate) mod tests { assert_eq!(r.waterfall.compares.len(), 2); assert_eq!(r.waterfall.reads.len(), 4); } - - pub(crate) fn joined_with_redundant_write() -> Vec { - let mut words = WATERFALL_JOINED_WAVE32.to_vec(); - let at = word_at(&words, 0x887E_147E) + 1; - words.splice( - at..at, - [ - 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 - 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo - 0x7E08_0218, // v_mov_b32 v4, s24 (then arm's word 0) - 0xBEFE_0312, // s_mov_b32 exec_lo, s18 - ], - ); - words - } - - /// 32-thread synthetic compute shader joining two 4-dword sampler - /// descriptors across an if/else (`lane < 16` takes entry 0, else entry 1) - /// and sampling a 2x1 texture at U=2.0. - pub(crate) fn joined_sampler_shader(redundant_write: Option) -> Vec { - let mut words = vec![ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xBE86_0301, // s_mov_b32 s6, s1 - 0xBE87_0380, // s_mov_b32 s7, 0 - 0xF40C_0202, - 0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0x0 - 0xF408_0603, - 0xFA00_0000, // s_load_dwordx4 s[24:27], s[6:7], 0x0 - 0xF408_0703, - 0xFA00_0010, // s_load_dwordx4 s[28:31], s[6:7], 0x10 - 0xF408_0A02, - 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 - 0x7E04_02F4, // v_mov_b32 v2, 2.0 - 0x7E06_0280, // v_mov_b32 v3, 0 - 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 - 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo - 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 - 0xBF88_0004, // s_cbranch_execz -> +4 (else flow) - 0x7E08_0218, // v_mov_b32 v4, s24 - 0x7E0A_0219, // v_mov_b32 v5, s25 - 0x7E0C_021A, // v_mov_b32 v6, s26 - 0x7E0E_021B, // v_mov_b32 v7, s27 - 0xBE94_3D14, // s_or_saveexec_b32 s20, s20 - 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 - 0xBF88_0004, // s_cbranch_execz -> +4 (join) - 0x7E08_021C, // v_mov_b32 v4, s28 - 0x7E0A_021D, // v_mov_b32 v5, s29 - 0x7E0C_021E, // v_mov_b32 v6, s30 - 0x7E0E_021F, // v_mov_b32 v7, s31 - 0x887E_147E, // s_or_b32 exec_lo, exec_lo, s20 - ]; - if let Some(mov) = redundant_write { - words.extend([ - 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 - 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo - mov, - 0xBEFE_0312, // s_mov_b32 exec_lo, s18 - ]); - } - words.extend([ - 0xBE97_037E, // s_mov_b32 s23, exec_lo - 0x7E20_0504, // loop: v_readfirstlane_b32 s16, v4 - 0x7E22_0505, // v_readfirstlane_b32 s17, v5 - 0x7E24_0506, // v_readfirstlane_b32 s18, v6 - 0x7E26_0507, // v_readfirstlane_b32 s19, v7 - 0xD4E2_0015, - 0x0002_0810, // v_cmp_eq_u64_e64 s21, s[16:17], v[4:5] - 0xD4E2_0016, - 0x0002_0C12, // v_cmp_eq_u64_e64 s22, s[18:19], v[6:7] - 0x8715_1615, // s_and_b32 s21, s21, s22 - 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 - 0xBF80_0000, // s_nop 0 - 0xF09C_0F08, - 0x0082_0C02, // image_sample_lz v[12:15], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D - 0xBF8C_3F70, // s_waitcnt vmcnt(0) - 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 - 0xBF89_FFF0, // s_cbranch_execnz -> loop (-16 dwords) - 0xBEFE_0317, // s_mov_b32 exec_lo, s23 - 0xE070_1000, - 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen - 0xBF81_0000, // s_endpgm - ]); - words - } - - #[test] - fn joined_descriptor_redundant_partial_write() { - let r = waterfall(&joined_with_redundant_write(), false).unwrap(); - let image = r - .descriptors - .iter() - .find(|d| matches!(d.source, Source::LanePhi { .. })) - .unwrap(); - let Source::LanePhi { args, .. } = &image.source else { - unreachable!() - }; - let [Some(Source::LanePhi { args: flow, .. }), Some(other)] = &args[..] else { - panic!("{args:?}") - }; - assert_eq!(table_offset(&r, other), 0x20); - let [None, Some(then)] = &flow[..] else { - panic!("{flow:?}") - }; - assert_eq!(table_offset(&r, then), 0); - assert_eq!(r.waterfall.compares.len(), 4); - assert_eq!(r.waterfall.reads.len(), 8); - } - - #[test] - fn joined_descriptor_redundant_partial_write_subset_and_swapped_cmp() { - // Strict subset mask (lane < 8) writing v4 = s24. - let mut subset = joined_with_redundant_write(); - let cmp = word_at(&subset, 0x7D88_0090); - let second_cmp = cmp - + 1 - + subset[cmp + 1..] - .iter() - .position(|&w| w == 0x7D88_0090) - .unwrap(); - subset[second_cmp] = 0x7D88_0088; // v_cmp_gt_u32 vcc_lo, 8, v0 - assert!(waterfall(&subset, false).is_ok()); - - // Swapped VOP3 comparison: v_cmp_lt_u32 vcc_lo, v0, 16. - let mut swapped = WATERFALL_JOINED_WAVE32.to_vec(); - let at = word_at(&swapped, 0x887E_147E) + 1; - swapped.splice( - at..at, - [ - 0xD4C1_006A, - 0x0001_2100, // v_cmp_lt_u32 vcc_lo, v0, 16 - 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo - 0x7E08_0218, // v_mov_b32 v4, s24 - 0xBEFE_0312, // s_mov_b32 exec_lo, s18 - ], - ); - assert!(waterfall(&swapped, false).is_ok()); - - // Independent sampler control (#750): redundant v4 = s24 passes, non-identity v4 = s28 fails. - assert!(waterfall(&joined_sampler_shader(Some(0x7E08_0218)), false).is_ok()); - assert_eq!( - refusal(&joined_sampler_shader(Some(0x7E08_021C)), false), - "a per-lane descriptor written where some lanes may keep the old one" - ); - } - - #[test] - fn joined_descriptor_non_identity_or_overlapping_partial_writes_are_refused() { - // Non-identity masked write: v4 = s32 on lanes < 16 corrupts the then-arm descriptor. - let mut wrong_val = joined_with_redundant_write(); - let mov = word_at(&wrong_val, 0xBE92_3C6A) + 1; - wrong_val[mov] = 0x7E08_0220; // v_mov_b32 v4, s32 - assert_eq!( - refusal(&wrong_val, false), - "a per-lane descriptor written where some lanes may keep the old one" - ); - - // Overlapping masked write: widen mask to lane < 24 so lanes 16..23 overwrite else-arm word 0. - let mut widened = joined_with_redundant_write(); - let cmp = word_at(&widened, 0xBE92_3C6A) - 1; - widened[cmp] = 0x7D88_0098; // v_cmp_gt_u32 vcc_lo, 24, v0 - assert_eq!( - refusal(&widened, false), - "a per-lane descriptor written where some lanes may keep the old one" - ); - - // Opposite-arm non-matching write: v_cmp_le_u32 16, v0 (lanes >= 16) writing s24. - let mut flipped = WATERFALL_JOINED_WAVE32.to_vec(); - let at = word_at(&flipped, 0x887E_147E) + 1; - flipped.splice( - at..at, - [ - 0x7D86_0090, // v_cmp_le_u32 vcc_lo, 16, v0 - 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo - 0x7E08_0218, // v_mov_b32 v4, s24 - 0xBEFE_0312, // s_mov_b32 exec_lo, s18 - ], - ); - assert_eq!( - refusal(&flipped, false), - "a per-lane descriptor written where some lanes may keep the old one" - ); - } - - pub(crate) fn fetched_with_lane_preserving_transforms() -> Vec { - let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); - // After global_load_dwordx4 v[4:7], v[8:11] and s_waitcnt (0xBF8C_0070), - // shuffle/identity-move/extract the loaded descriptor dwords before the waterfall loop. - let at = word_at(&words, 0xBF8C_0070) + 1; - words.splice( - at..at, - [ - // v_swap_b32 v4, v5; v_swap_b32 v5, v4 (back to original order via swaps) - 0x7E08_CB05, - 0x7E0A_CB04, - // Identity bitwise/shift moves: v4 = 0 | v4, v5 = -1 & v5, v6 = v6 << 0 - 0x3808_0880, - 0x360A_0AC1, - 0x340C_0C80, - // 64-bit word extract: v_lshrrev_b64 v[20:21], 32, v[6:7] -> v20 = v7 - 0xD700_0014, - 0x0002_0CA0, - // v_mov_b32 v7, v20 - 0x7E0E_0314, - // Byte-preserving v_perm_b32 v22, v8, v9, 0x07060504 -> v22 = v8 - 0xD744_0016, - 0x03FE_1308, - 0x0706_0504, - // v_mov_b32 v8, v22 - 0x7E10_0316, - // v_alignbit_b32 v23, v8, v9, 0 -> v23 = v9 - 0xD54E_0017, - 0x0202_1308, - // v_mov_b32 v9, v23 - 0x7E12_0317, - // v_cndmask_b32 v10, v10, v10, vcc_lo (same operand on both sides) - 0x0214_150A, - ], - ); - // Adjust s_cbranch_execnz backward offset in loop by +16 dwords (-0x1a - 16 = -0x2a) — - // wait: the loop starts AFTER `at`, so its own backward offset is unchanged! - words - } - - #[test] - fn first_lane_of_lane_preserving_moves_and_extracts_is_traced() { - let r = waterfall(&fetched_with_lane_preserving_transforms(), false).unwrap(); - let image = r - .descriptors - .iter() - .find(|d| d.role == Role::Resource) - .unwrap(); - assert!(matches!(image.source, Source::Fetched { first: 0, .. })); - assert_eq!(r.waterfall.compares.len(), 4); - assert_eq!(r.waterfall.reads.len(), 8); - } - - #[test] - fn first_lane_of_non_identity_computed_vgprs_still_fails() { - let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); - let at = word_at(&words, 0xBF8C_0070) + 1; - // Non-identity computed VGPR: v_or_b32 v4, 1, v4 - words.insert(at, 0x3808_0881); - assert_eq!( - refusal(&words, false), - "a descriptor read from the first lane of computed VGPRs" - ); - - // Non-dword 64-bit shift: v_lshrrev_b64 v[20:21], 16, v[6:7]; v_mov_b32 v4, v20 - let mut bad_shift = WATERFALL_FETCHED_WAVE32.to_vec(); - bad_shift.splice( - at..at, - [ - 0xD700_0014, - 0x0002_0C90, // shift by 16 - 0x7E08_0314, // v4 = v20 - ], - ); - assert_eq!( - refusal(&bad_shift, false), - "a descriptor read from the first lane of computed VGPRs" - ); - - // Non-identity permute selector: 0x07060405 into v4 - let mut bad_perm = WATERFALL_FETCHED_WAVE32.to_vec(); - bad_perm.splice( - at..at, - [ - 0xD744_0016, - 0x03FE_1308, - 0x0706_0405, - 0x7E08_0316, // v4 = v22 - ], - ); - assert_eq!( - refusal(&bad_perm, false), - "a descriptor read from the first lane of computed VGPRs" - ); - - // Guarded v_swap_b32 under partial EXEC (not redundant since v4 != v5) must fail. - let mut guarded_swap = WATERFALL_FETCHED_WAVE32.to_vec(); - guarded_swap.splice( - at..at, - [ - 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 - 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo - 0x7E08_CB05, // v_swap_b32 v4, v5 - 0xBEFE_0312, // s_mov_b32 exec_lo, s18 - ], - ); - assert_eq!( - refusal(&guarded_swap, false), - "a per-lane descriptor written where some lanes may keep the old one" - ); - } - - #[test] - fn lane_select_accepts_equivalent_masks_and_refuses_different_ones() { - // Recompute an equivalent mask in s18 for the high word of WATERFALL_PICKED_WAVE32 - // and verify it still traces, while a narrower mask (lane < 8) is refused. - let mut eq_mask = WATERFALL_PICKED_WAVE32.to_vec(); - let at = word_at(&eq_mask, 0x0216_1627); - eq_mask.splice( - at..at, - [ - 0xD4C1_0012, - 0x0001_2100, // v_cmp_lt_u32_e64 s18, v0, 16 - ], - ); - let cnd = at + 2; - // Replace v_cndmask_b32 v11, s39, v11, vcc_lo with VOP3 using s18. - eq_mask[cnd] = 0xD501_000B; - eq_mask.insert(cnd + 1, (18 << 18) | ((256 + 11) << 9) | 39); - assert!(waterfall(&eq_mask, false).is_ok()); - - let mut diff_mask = eq_mask; - diff_mask[at + 1] = 0x0001_1100; // v_cmp_lt_u32_e64 s18, v0, 8 - assert_eq!( - refusal(&diff_mask, false), - "a descriptor chosen per lane by several masks" - ); - } - - #[test] - fn v_cndmask_literal_all_ones_mask_is_refused_in_wave64() { - // v_cndmask_b32_e64 v4, v20, v4, 0xFFFF_FFFF: in wave32 all 32 lanes - // take v4 (set), whereas in wave64 the literal zero-extends to - // 0x0000_0000_FFFF_FFFF so lanes 32..63 take v20 (clear). - let lit_mask = [ - 0xD501_0004, - (255 << 18) | ((256 + 4) << 9) | (256 + 20), - u32::MAX, - ]; - let mut w32 = WATERFALL_FETCHED_WAVE32.to_vec(); - let at32 = word_at(&w32, 0xBF8C_0070) + 1; - w32.splice(at32..at32, lit_mask); - assert!(waterfall(&w32, false).is_ok()); - - let mut w64_lit = WATERFALL_FETCHED_WAVE64.to_vec(); - let at64 = word_at(&w64_lit, 0xBF8C_0070) + 1; - w64_lit.splice(at64..at64, lit_mask); - assert_eq!( - refusal(&w64_lit, true), - "a descriptor read from the first lane of computed VGPRs" - ); - - // Inline -1 (Const(193)) sign-extends to all 64 lanes in wave64. - let mut w64_inline = WATERFALL_FETCHED_WAVE64.to_vec(); - w64_inline.splice( - at64..at64, - [0xD501_0004, (193 << 18) | ((256 + 4) << 9) | (256 + 20)], - ); - assert!(waterfall(&w64_inline, true).is_ok()); - } - - #[test] - fn joined_descriptor_redundant_partial_write_w16() { - // After the if/else join of WATERFALL_JOINED_WAVE32, re-writing v4 - // with s24 under the same lane < 16 predicate leaves every lane's - // descriptor unchanged. - let mut words = WATERFALL_JOINED_WAVE32.to_vec(); - let at = words.iter().position(|&w| w == 0x887E_147E).unwrap() + 1; - words.splice( - at..at, - [ - 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 (lane < 16) - 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo - 0x7E08_0218, // v_mov_b32 v4, s24 (same word the then arm wrote) - 0xBEFE_0312, // s_mov_b32 exec_lo, s18 - ], - ); - let r = waterfall(&words, false).unwrap(); - let image = r - .descriptors - .iter() - .find(|d| d.role == Role::Resource && matches!(d.source, Source::LanePhi { .. })) - .unwrap(); - let offsets: Vec = image - .source - .leaves() - .into_iter() - .map(|s| table_offset(&r, s)) - .collect(); - assert_eq!(offsets, vec![0, 0x20]); - } - - #[test] - fn joined_descriptor_redundant_partial_write_negated_compare() { - // Same as above, targeting the else arm (lane >= 16) via the negated - // integer compare `v_cmp_le_u32 16, v0` and writing s32 to v4. - let mut words = WATERFALL_JOINED_WAVE32.to_vec(); - let at = words.iter().position(|&w| w == 0x887E_147E).unwrap() + 1; - words.splice( - at..at, - [ - 0x7D86_0090, // v_cmp_le_u32 vcc_lo, 16, v0 (lane >= 16) - 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo - 0x7E08_0220, // v_mov_b32 v4, s32 (same word the else arm wrote) - 0xBEFE_0312, // s_mov_b32 exec_lo, s18 - ], - ); - let r = waterfall(&words, false).unwrap(); - let image = r - .descriptors - .iter() - .find(|d| d.role == Role::Resource && matches!(d.source, Source::LanePhi { .. })) - .unwrap(); - let offsets: Vec = image - .source - .leaves() - .into_iter() - .map(|s| table_offset(&r, s)) - .collect(); - assert_eq!(offsets, vec![0, 0x20]); - } - - #[test] - fn joined_descriptor_non_redundant_partial_write_fails() { - // Writing the else arm's word (s32) under the then arm's mask - // (lane < 16) changes active lanes' v4 and must still be refused. - let mut words = WATERFALL_JOINED_WAVE32.to_vec(); - let at = words.iter().position(|&w| w == 0x887E_147E).unwrap() + 1; - words.splice( - at..at, - [ - 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 (lane < 16) - 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo - 0x7E08_0220, // v_mov_b32 v4, s32 (wrong arm's word) - 0xBEFE_0312, // s_mov_b32 exec_lo, s18 - ], - ); - let err = waterfall(&words, false).unwrap_err(); - assert!( - matches!( - err, - ShaderError::Unsupported { - what: "a per-lane descriptor written where some lanes may keep the old one", - .. - } - ), - "{err:?}" - ); - } - - #[test] - fn joined_descriptor_wider_mask_partial_write_fails() { - // Writing s24 under lane < 24 overwrites lanes 16..24 (which held s32) - // and must still be refused. - let mut words = WATERFALL_JOINED_WAVE32.to_vec(); - let at = words.iter().position(|&w| w == 0x887E_147E).unwrap() + 1; - words.splice( - at..at, - [ - 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0 (lane < 24) - 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo - 0x7E08_0218, // v_mov_b32 v4, s24 - 0xBEFE_0312, // s_mov_b32 exec_lo, s18 - ], - ); - let err = waterfall(&words, false).unwrap_err(); - assert!( - matches!( - err, - ShaderError::Unsupported { - what: "a per-lane descriptor written where some lanes may keep the old one", - .. - } - ), - "{err:?}" - ); - } } diff --git a/crates/victory-shader/src/resource/uniform.rs b/crates/victory-shader/src/resource/uniform.rs deleted file mode 100644 index a531c8b..0000000 --- a/crates/victory-shader/src/resource/uniform.rs +++ /dev/null @@ -1,289 +0,0 @@ -//! Wave uniformity through phis: a loop counter or a value joined by a -//! uniform branch holds the same value in every lane that runs, so an -//! address computed from it and read back with `v_readfirstlane_b32` is the -//! address of every lane (the console compiler's table loops). -//! -//! A phi is uniform when all its arguments are, and no branch whose lanes -//! may part ways can send lanes to it along different edges: not a join of -//! the two arms of such a branch, nor a block of a loop it can leave or -//! stay in lane by lane. The set of uniform phis is the greatest fixed -//! point (a loop counter's own increment feeds its exit test). - -use super::{MAX_ROUNDS, Tracer}; -use crate::ir::{EXEC, Exit, Inst, Reg, VCC, Value, reverse_postorder}; - -/// Operations that combine lane masks bit by bit (or copy one). -const MASK_OPS: &[&str] = &[ - "s_and_b32", - "s_or_b32", - "s_xor_b32", - "s_andn2_b32", - "s_orn2_b32", - "s_nand_b32", - "s_nor_b32", - "s_xnor_b32", - "s_and_b64", - "s_or_b64", - "s_xor_b64", - "s_andn2_b64", - "s_orn2_b64", - "s_mov_b32", - "s_mov_b64", - "s_not_b32", - "s_not_b64", -]; - -/// Per block: the blocks a lane-divergent branch there taints. -pub(super) type Regions = Vec>>; - -fn is_exec(reg: Reg) -> bool { - matches!(reg, Reg::S(c) if c == EXEC || c == EXEC + 1) -} - -impl Tracer<'_> { - /// Whether the phi `v` is the same in every lane that reads it. - pub(super) fn phi_uniform(&self, v: Value) -> bool { - if self.lanes.is_none() { - return false; - } - if self.phi_ok.borrow().is_none() { - self.settle_phis(); - } - self.phi_ok - .borrow() - .as_ref() - .is_some_and(|ok| ok[v.0 as usize]) - } - - /// Greatest fixed point: every phi uniform until an argument or a - /// divergent branch says otherwise. - fn settle_phis(&self) { - let mut ok: Vec = self.phis.iter().map(Option::is_some).collect(); - *self.phi_ok.borrow_mut() = Some(ok.clone()); - let regions = self.regions(); - let mut settled = false; - for _ in 0..MAX_ROUNDS { - self.uniform_memo.borrow_mut().fill(None); - let mut tainted = vec![false; self.p.blocks.len()]; - for (b, region) in regions.iter().enumerate() { - if let Some(region) = region - && !self.branch_uniform(b) - { - for &x in region { - tainted[x] = true; - } - } - } - let mut changed = false; - for (b, block) in self.p.blocks.iter().enumerate() { - for phi in &block.phis { - let i = phi.value.0 as usize; - if ok[i] && (tainted[b] || !phi.args.iter().all(|&a| self.uniform(a))) { - ok[i] = false; - changed = true; - } - } - } - *self.phi_ok.borrow_mut() = Some(ok.clone()); - if !changed { - settled = true; - break; - } - } - if !settled { - *self.phi_ok.borrow_mut() = Some(vec![false; ok.len()]); - } - self.uniform_memo.borrow_mut().fill(None); - } - - /// Whether every lane that reaches the closing branch of block `b` - /// takes it the same way. - fn branch_uniform(&self, b: usize) -> bool { - let Some(inst) = self.p.blocks[b].insts.last() else { - return false; - }; - match inst.name() { - "s_cbranch_execz" | "s_cbranch_execnz" => true, - "s_cbranch_scc0" | "s_cbranch_scc1" => { - inst.read(Reg::Scc).is_some_and(|v| self.uniform(v)) - } - "s_cbranch_vccz" | "s_cbranch_vccnz" => { - let mut vcc = inst - .reads - .iter() - .filter(|(r, _)| matches!(r, Reg::S(c) if (VCC..VCC + 2).contains(c))) - .peekable(); - vcc.peek().is_some() && vcc.all(|&(_, v)| self.mask_uniform(v)) - } - _ => false, - } - } - - /// Whether a lane mask holds the same bit in every lane it covers: a - /// comparison of uniform values, combined with EXEC and other such masks. - fn mask_uniform(&self, v: Value) -> bool { - let Some(inst) = self.def(v) else { - return false; - }; - let name = inst.name(); - if name.starts_with("v_cmp") && !name.starts_with("v_cmpx") { - return self.valu_reads_uniform(inst, false); - } - MASK_OPS.contains(&name) - && inst.reads.iter().all(|&(reg, x)| { - is_exec(reg) || (reg != Reg::Scc && (self.mask_uniform(x) || self.uniform(x))) - }) - } - - /// Whether every register a VALU instruction reads is uniform, but EXEC - /// and, unless `guarded`, the old value of the VGPRs it writes (which - /// only the lanes it skips keep). - pub(super) fn valu_reads_uniform(&self, inst: &Inst, guarded: bool) -> bool { - inst.reads.iter().all(|&(reg, x)| { - is_exec(reg) - || (!guarded && matches!(reg, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == reg)) - || self.uniform(x) - }) - } - - /// Whether lanes run the instruction defining `v` under a condition - /// beyond reaching it. - pub(super) fn guarded(&self, v: Value) -> bool { - match (self.lanes, self.defs[v.0 as usize]) { - (Some(st), Some((b, i))) => st.guards[b][i].is_some(), - _ => true, - } - } - - /// The blocks tainted by the branch closing each block, were it divergent. - fn regions(&self) -> &Regions { - self.regions.get_or_init(|| { - let blocks = &self.p.blocks; - let n = blocks.len(); - let mut fwd = vec![false; n]; - for b in reverse_postorder(blocks) { - fwd[b] = true; - } - let succs: Vec> = blocks - .iter() - .map(|b| match b.exit { - Exit::Jump(t) => vec![t], - Exit::Branch { taken, not_taken } => vec![taken, not_taken], - Exit::End => vec![n], - Exit::Indirect => Vec::new(), - }) - .collect(); - let (_, ipdom) = compute_postdoms(n, &succs, &fwd); - let walk = |from: usize, stop: usize, next: &dyn Fn(usize) -> Vec| { - let mut seen = vec![false; n]; - let mut stack = vec![from]; - while let Some(x) = stack.pop() { - if x >= n || seen[x] { - continue; - } - seen[x] = true; - if x != stop { - stack.extend(next(x)); - } - } - seen - }; - let forward = |x: usize| succs[x].clone(); - let backward = |x: usize| blocks[x].preds.clone(); - (0..n) - .map(|b| { - let Exit::Branch { taken, not_taken } = blocks[b].exit else { - return None; - }; - if !fwd[b] || taken == not_taken { - return None; - } - let stop = ipdom[b]; - let (r1, r2) = (walk(taken, stop, &forward), walk(not_taken, stop, &forward)); - // Its loop: the blocks it reaches that reach it back. - let (d1, d2) = ( - walk(taken, usize::MAX, &forward), - walk(not_taken, usize::MAX, &forward), - ); - let up = walk(b, usize::MAX, &backward); - Some( - (0..n) - .filter(|&x| (r1[x] && r2[x]) || ((d1[x] || d2[x]) && up[x])) - .collect(), - ) - }) - .collect() - }) - } -} - -/// Immediate post-dominator per block (or virtual exit `n`) using Cooper-Harvey-Kennedy. -/// Unreachable or never-exiting blocks have `rev_idx == usize::MAX`. -fn compute_postdoms(n: usize, succs: &[Vec], fwd: &[bool]) -> (Vec, Vec) { - let mut rev_succs = vec![Vec::new(); n + 1]; - for b in 0..n { - if !fwd[b] { - continue; - } - for &s in &succs[b] { - rev_succs[s].push(b); - } - } - let mut post = Vec::with_capacity(n + 1); - let mut seen = vec![false; n + 1]; - let mut stack = vec![(n, 0usize)]; - seen[n] = true; - while let Some((node, idx)) = stack.last_mut() { - let u = *node; - if *idx < rev_succs[u].len() { - let v = rev_succs[u][*idx]; - *idx += 1; - if !seen[v] { - seen[v] = true; - stack.push((v, 0)); - } - } else { - post.push(u); - stack.pop(); - } - } - post.reverse(); - let mut rev_idx = vec![usize::MAX; n + 1]; - for (idx, &b) in post.iter().enumerate() { - rev_idx[b] = idx; - } - let mut ipdom = vec![usize::MAX; n + 1]; - ipdom[n] = n; - let intersect = |mut a: usize, mut b: usize, ipdom: &[usize]| -> usize { - while a != b { - while rev_idx[a] > rev_idx[b] { - a = ipdom[a]; - } - while rev_idx[b] > rev_idx[a] { - b = ipdom[b]; - } - } - a - }; - let mut changed = true; - while changed { - changed = false; - for &b in &post[1..] { - let mut new = usize::MAX; - for &s in &succs[b] { - if ipdom[s] != usize::MAX { - new = if new == usize::MAX { - s - } else { - intersect(s, new, &ipdom) - }; - } - } - if new != usize::MAX && ipdom[b] != new { - ipdom[b] = new; - changed = true; - } - } - } - (rev_idx, ipdom) -} diff --git a/crates/victory-shader/src/spill.rs b/crates/victory-shader/src/spill.rs index 28f728a..a0feb6a 100644 --- a/crates/victory-shader/src/spill.rs +++ b/crates/victory-shader/src/spill.rs @@ -55,7 +55,7 @@ fn spilled(native: &NativeProgram) -> Option> { } /// Whether `native` reads its root parameters from a spilled user-data -/// table. (In Grand Theft Auto VI exactly the compute programs of the +/// table. (In the title exactly the compute programs of the /// console's ray-tracing structure builder do.) pub fn is_spilled(native: &NativeProgram) -> bool { spilled(native).is_some() @@ -170,16 +170,11 @@ pub fn user_data(p: &mut Program, native: &NativeProgram) -> usize { continue; }; if !inst.name().starts_with("s_load_dword") - || !matches!( - soffset, - Operand::Scalar { code: NULL, .. } | Operand::Const(128) - ) + || !matches!(soffset, Operand::Scalar { code: NULL, .. } | Operand::Const(128)) || offset < 0 || offset % 4 != 0 || !inst.read(Reg::S(base)).is_some_and(|v| lows.contains(&v)) - || !inst - .read(Reg::S(base + 1)) - .is_some_and(|v| highs.contains(&v)) + || !inst.read(Reg::S(base + 1)).is_some_and(|v| highs.contains(&v)) { continue; } @@ -344,12 +339,7 @@ mod tests { ); let mut p = ir::build(&n.code, false, 256).unwrap(); assert_eq!(user_data(&mut p, &n), 2); - let names: Vec<&str> = p - .blocks - .iter() - .flat_map(|b| &b.insts) - .map(|i| i.name()) - .collect(); + let names: Vec<&str> = p.blocks.iter().flat_map(|b| &b.insts).map(|i| i.name()).collect(); assert!(!names.iter().any(|n| n.starts_with("s_load_")), "{names:?}"); // The pointer is gone with the loads; byte 0x10 is index 20, the // first root constant, and bytes 0-7 are the first root view. diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index 918d666..a913176 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -68,7 +68,6 @@ pub struct Bools { /// The tables below have small integer keys; SipHash dominated run time. type Map = HashMap>; -type Set = HashSet>; /// FxHash's multiply-rotate step. #[derive(Default)] @@ -144,17 +143,14 @@ impl Bools { } fn vars(&self, b: Bool) -> Vec { - let mut seen = Set::default(); - let mut has_var = vec![false; self.atoms.len()]; - let mut vars = Vec::new(); - let mut stack = vec![b]; + let (mut seen, mut vars, mut stack) = (Vec::new(), Vec::new(), vec![b]); while let Some(b) = stack.pop() { let (v, lo, hi) = self.nodes[b.0 as usize]; - if v == TERMINAL || !seen.insert(b) { + if v == TERMINAL || seen.contains(&b) { continue; } - if !has_var[v as usize] { - has_var[v as usize] = true; + seen.push(b); + if !vars.contains(&v) { vars.push(v); } stack.extend([lo, hi]); @@ -197,13 +193,7 @@ impl Bools { } } - fn ite(&mut self, mut f: Bool, mut g: Bool, mut h: Bool) -> Bool { - if f == g { - g = Bool::TRUE; - } - if f == h { - h = Bool::FALSE; - } + fn ite(&mut self, f: Bool, g: Bool, h: Bool) -> Bool { if f == Bool::TRUE || g == h { return g; } @@ -213,14 +203,6 @@ impl Bools { if (g, h) == (Bool::TRUE, Bool::FALSE) { return f; } - if self.overflow { - return Bool::FALSE; - } - if h == Bool::FALSE && f > g { - std::mem::swap(&mut f, &mut g); - } else if g == Bool::TRUE && f > h { - std::mem::swap(&mut f, &mut h); - } if let Some(&r) = self.memo.get(&(f, g, h)) { return r; } @@ -350,139 +332,16 @@ impl Bools { found } - /// The `Bool` representing `atom` if it exists in this table. - pub(crate) fn var_bool(&self, atom: Atom) -> Option { - let &v = self.ids.get(&atom)?; - self.unique.get(&(v, Bool::FALSE, Bool::TRUE)).copied() - } - - /// Whether some lane can satisfy every `(b, holds)` of `all` at once, - /// enforcing equivalence groups over atoms (`(atom, group, inverted)`) - /// and checking `leaf_ok` on any surviving leaf assignment. - pub(crate) fn meet_with_facts( - &self, - all: &[(Bool, bool)], - equiv: &[(Atom, usize, bool)], - groups_len: usize, - leaf_ok: impl Fn(&[(Atom, bool)]) -> bool, - ) -> bool { - let mut var_equiv = Map::default(); - for &(atom, group, inv) in equiv { - if let Some(&v) = self.ids.get(&atom) { - var_equiv.insert(v, (group, inv)); - } - } - let mut budget = MAX_MEET; - let mut groups = vec![None; groups_len]; - let mut assigned = Vec::new(); - self.meet_facts_in( - all.to_vec(), - &mut budget, - &var_equiv, - &mut groups, - &mut assigned, - &leaf_ok, - ) - } - - fn meet_facts_in bool>( - &self, - mut all: Vec<(Bool, bool)>, - budget: &mut usize, - var_equiv: &Map, - groups: &mut [Option], - assigned: &mut Vec<(Atom, bool)>, - leaf_ok: &F, - ) -> bool { - let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE }; - if all.iter().any(fails) { - return false; - } - all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE); - if *budget == 0 { - return true; - } - if all.is_empty() { - return leaf_ok(assigned); - } - *budget -= 1; - let top = |b: Bool| self.nodes[b.0 as usize].0; - let v = all.iter().map(|&(b, _)| top(b)).min().expect("not empty"); - let atom = self.atoms[v as usize]; - let track_atom = matches!(atom, Atom::Lane(_)); - - let values = match var_equiv.get(&v).copied() { - Some((g, inv)) => match groups[g] { - Some(gval) => [Some(gval ^ inv), None], - None => [Some(false), Some(true)], - }, - None => [Some(false), Some(true)], - }; - - for value in values.into_iter().flatten() { - let set_group = match var_equiv.get(&v).copied() { - Some((g, inv)) if groups[g].is_none() => { - groups[g] = Some(value ^ inv); - Some(g) - } - _ => None, - }; - let next = all - .iter() - .map(|&(b, holds)| { - let (lo, hi) = self.split(b, v); - (if value { hi } else { lo }, holds) - }) - .collect(); - if track_atom { - assigned.push((atom, value)); - } - let ok = self.meet_facts_in(next, budget, var_equiv, groups, assigned, leaf_ok); - if track_atom { - assigned.pop(); - } - if let Some(g) = set_group { - groups[g] = None; - } - if ok { - return true; - } - } - false - } - - fn implies(&self, a: Bool, b: Bool) -> bool { - fn check(bools: &Bools, a: Bool, b: Bool, memo: &mut Map<(Bool, Bool), bool>) -> bool { - if a == Bool::FALSE || b == Bool::TRUE || a == b { - return true; - } - if a == Bool::TRUE || b == Bool::FALSE { - return false; - } - if let Some(&r) = memo.get(&(a, b)) { - return r; - } - let v = bools.nodes[a.0 as usize].0.min(bools.nodes[b.0 as usize].0); - let ((a0, a1), (b0, b1)) = (bools.split(a, v), bools.split(b, v)); - let r = check(bools, a0, b0, memo) && check(bools, a1, b1, memo); - memo.insert((a, b), r); - r - } - - if a == Bool::FALSE || b == Bool::TRUE || a == b { - return true; - } - if a == Bool::TRUE || b == Bool::FALSE { - return false; - } - check(self, a, b, &mut Map::default()) + fn implies(&mut self, a: Bool, b: Bool) -> bool { + let nb = self.not(b); + self.and(a, nb) == Bool::FALSE } /// `b` with every atom born at reverse-postorder index `from` or later /// existentially quantified: what still holds once those are redefined. fn forget(&mut self, b: Bool, from: usize, memo: &mut Map) -> Bool { let (v, lo, hi) = self.nodes[b.0 as usize]; - if v == TERMINAL || self.overflow { + if v == TERMINAL { return b; } if let Some(&r) = memo.get(&b) { @@ -499,112 +358,6 @@ impl Bools { r } - /// For each atom index, the value `known` decides it to, if any. - /// Empty when `known` forces no atom. - fn forced(&self, known: Bool) -> Vec> { - let n = self.atoms.len(); - if known == Bool::TRUE || n == 0 { - return Vec::new(); - } - if known == Bool::FALSE { - return vec![Some(true); n]; - } - let mut seen = Set::default(); - let mut stack = vec![known]; - let mut skip_diff = vec![0i32; n + 1]; - let mut can_false = vec![false; n]; - let mut can_true = vec![false; n]; - - let root_var = self.nodes[known.0 as usize].0 as usize; - if root_var > 0 { - skip_diff[0] += 1; - skip_diff[root_var] -= 1; - } - - while let Some(u) = stack.pop() { - let (v, lo, hi) = self.nodes[u.0 as usize]; - if v == TERMINAL || !seen.insert(u) { - continue; - } - let v = v as usize; - if lo != Bool::FALSE { - can_false[v] = true; - let lo_var = self.nodes[lo.0 as usize].0; - let end = if lo_var == TERMINAL { - n - } else { - lo_var as usize - }; - if v + 1 < end { - skip_diff[v + 1] += 1; - skip_diff[end] -= 1; - } - stack.push(lo); - } - if hi != Bool::FALSE { - can_true[v] = true; - let hi_var = self.nodes[hi.0 as usize].0; - let end = if hi_var == TERMINAL { - n - } else { - hi_var as usize - }; - if v + 1 < end { - skip_diff[v + 1] += 1; - skip_diff[end] -= 1; - } - stack.push(hi); - } - } - - let mut out = Vec::with_capacity(n); - let mut skipped = 0i32; - let mut any = false; - for ((&diff, &f), &t) in skip_diff[..n].iter().zip(&can_false).zip(&can_true) { - skipped += diff; - let val = if skipped == 0 && f != t { - any = true; - Some(t) - } else { - None - }; - out.push(val); - } - if !any { - out.clear(); - } - out - } - - fn restrict_many( - &mut self, - b: Bool, - forced: &[Option], - memo: &mut Map, - ) -> Bool { - if forced.is_empty() || self.overflow { - return b; - } - let (bv, lo, hi) = self.nodes[b.0 as usize]; - if bv == TERMINAL { - return b; - } - if let Some(&r) = memo.get(&b) { - return r; - } - let r = match forced[bv as usize] { - Some(true) => self.restrict_many(hi, forced, memo), - Some(false) => self.restrict_many(lo, forced, memo), - None => { - let l = self.restrict_many(lo, forced, memo); - let h = self.restrict_many(hi, forced, memo); - self.mk(bv, l, h) - } - }; - memo.insert(b, r); - r - } - fn restrict(&mut self, b: Bool, v: u32, value: bool, memo: &mut Map) -> Bool { let (bv, lo, hi) = self.nodes[b.0 as usize]; if bv == TERMINAL || bv > v { @@ -638,162 +391,6 @@ impl Bools { } } -/// Non-mutating overlay over [`Bools`] for building path conditions in -/// lowering without mutating [`Structured`]. Caps extra nodes and falls back -/// to `Bool::TRUE` (conservatively reachable) on overflow. -pub(crate) struct BoolSet<'a> { - base: &'a Bools, - extra: Vec<(u32, Bool, Bool)>, - unique: Map<(u32, Bool, Bool), Bool>, - memo: Map<(Bool, Bool, Bool), Bool>, - forget_memo: Map<(Bool, usize), Bool>, - overflow: bool, -} - -const MAX_OVERLAY_NODES: usize = 1 << 16; - -impl<'a> BoolSet<'a> { - pub(crate) fn new(base: &'a Bools) -> Self { - BoolSet { - base, - extra: Vec::new(), - unique: Map::default(), - memo: Map::default(), - forget_memo: Map::default(), - overflow: false, - } - } - - fn node(&self, b: Bool) -> (u32, Bool, Bool) { - let base_len = self.base.nodes.len(); - let idx = b.0 as usize; - if idx < base_len { - self.base.nodes[idx] - } else { - self.extra[idx - base_len] - } - } - - fn mk(&mut self, v: u32, lo: Bool, hi: Bool) -> Bool { - if self.overflow { - return Bool::TRUE; - } - if lo == hi { - return lo; - } - let base_len = self.base.nodes.len(); - if (lo.0 as usize) < base_len - && (hi.0 as usize) < base_len - && let Some(&b) = self.base.unique.get(&(v, lo, hi)) - { - return b; - } - if let Some(&b) = self.unique.get(&(v, lo, hi)) { - return b; - } - if self.extra.len() >= MAX_OVERLAY_NODES { - self.overflow = true; - return Bool::TRUE; - } - let b = Bool((base_len + self.extra.len()) as u32); - self.extra.push((v, lo, hi)); - self.unique.insert((v, lo, hi), b); - b - } - - fn split(&self, b: Bool, v: u32) -> (Bool, Bool) { - match self.node(b) { - (bv, lo, hi) if bv == v => (lo, hi), - _ => (b, b), - } - } - - fn ite(&mut self, f: Bool, g: Bool, h: Bool) -> Bool { - if self.overflow { - return Bool::TRUE; - } - if f == Bool::TRUE || g == h { - return g; - } - if f == Bool::FALSE { - return h; - } - if (g, h) == (Bool::TRUE, Bool::FALSE) { - return f; - } - if let Some(&r) = self.memo.get(&(f, g, h)) { - return r; - } - let top = |b: Bool| self.node(b).0; - let v = top(f).min(top(g)).min(top(h)); - let ((f0, f1), (g0, g1), (h0, h1)) = (self.split(f, v), self.split(g, v), self.split(h, v)); - let lo = self.ite(f0, g0, h0); - let hi = self.ite(f1, g1, h1); - let r = self.mk(v, lo, hi); - self.memo.insert((f, g, h), r); - r - } - - pub(crate) fn and(&mut self, a: Bool, b: Bool) -> Bool { - self.ite(a, b, Bool::FALSE) - } - - pub(crate) fn or(&mut self, a: Bool, b: Bool) -> Bool { - self.ite(a, Bool::TRUE, b) - } - - pub(crate) fn not(&mut self, a: Bool) -> Bool { - match a { - Bool::FALSE if !self.overflow => Bool::TRUE, - Bool::TRUE if !self.overflow => Bool::FALSE, - _ => self.ite(a, Bool::FALSE, Bool::TRUE), - } - } - - /// Existentially quantifies atoms born at `from` or later (loop back edges). - pub(crate) fn forget(&mut self, b: Bool, from: usize) -> Bool { - if self.overflow { - return Bool::TRUE; - } - let (v, lo, hi) = self.node(b); - if v == TERMINAL { - return b; - } - if let Some(&r) = self.forget_memo.get(&(b, from)) { - return r; - } - let lo = self.forget(lo, from); - let hi = self.forget(hi, from); - let r = if self.base.born[v as usize] >= from { - self.or(lo, hi) - } else { - self.mk(v, lo, hi) - }; - self.forget_memo.insert((b, from), r); - r - } - - /// Condition under which a lane takes edge `q -> b`. - pub(crate) fn edge(&mut self, st: &Structured, q: usize, b: usize) -> Bool { - let mut c = st.reach[q]; - if let LaneExit::Branch { - when, - taken, - not_taken, - } = st.exits[q] - && taken != not_taken - { - let branch = if b == taken { when } else { self.not(when) }; - c = self.and(c, branch); - } - c - } - - pub(crate) fn sat(&mut self, a: Bool, b: Bool) -> bool { - self.overflow || self.and(a, b) != Bool::FALSE - } -} - /// How a lane leaves a block. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LaneExit { @@ -825,9 +422,6 @@ pub struct Structured { pub reach: Vec, /// The lane's bit of each lane-mask value, by its low dword's value. pub masks: HashMap, - /// Lane masks not derived from EXEC or VALU results (constants, opaque - /// values, uniform selects) resolved at uses such as `v_cndmask_b32`. - pub other: HashMap, /// Exact Wave64 pairs for checking masks at their uses. paired_masks: Map, /// Wave64 masks: low dword's value by the high dword's. @@ -1194,56 +788,39 @@ impl<'a> Lanes<'a> { } let blocks = &self.p.blocks; let b = &mut self.b; - let mut guards = Vec::with_capacity(blocks.len()); - let mut exits = Vec::with_capacity(blocks.len()); - let mut restrict_memo = Map::default(); - - for (n, block) in blocks.iter().enumerate() { - let reach = cond[n]; - let forced = b.forced(reach); - restrict_memo.clear(); - let mut last_exec: Option<(Bool, Option)> = None; - let block_guards = block - .insts - .iter() - .zip(&execs[n]) - .map(|(inst, exec)| match (exec, &inst.fields) { - (None, _) - | (_, Fields::Sop { .. } | Fields::Sopp { .. } | Fields::Smem { .. }) => None, - (&Some(e), _) => { - if let Some((prev, guard)) = last_exec - && prev == e - { - return guard; - } - let guard = if b.implies(reach, e) { + let guards = blocks + .iter() + .enumerate() + .map(|(n, block)| { + block + .insts + .iter() + .zip(&execs[n]) + .map(|(inst, exec)| match (exec, &inst.fields) { + (None, _) + | (_, Fields::Sop { .. } | Fields::Sopp { .. } | Fields::Smem { .. }) => { None - } else { - Some(b.restrict_many(e, &forced, &mut restrict_memo)) - }; - last_exec = Some((e, guard)); - guard - } - }) - .collect(); - guards.push(block_guards); - let exit = match block.exit { + } + (&Some(e), _) if b.implies(cond[n], e) => None, + (&Some(e), _) => Some(b.given(e, cond[n])), + }) + .collect() + }) + .collect(); + let exits = blocks + .iter() + .enumerate() + .map(|(n, block)| match block.exit { Exit::Jump(t) => LaneExit::Jump(t), Exit::End => LaneExit::End, Exit::Indirect => LaneExit::Indirect, Exit::Branch { taken, not_taken } => LaneExit::Branch { - when: b.restrict_many( - self.when[n].unwrap_or(Bool::FALSE), - &forced, - &mut restrict_memo, - ), + when: b.given(self.when[n].unwrap_or(Bool::FALSE), cond[n]), taken, not_taken, }, - }; - exits.push(exit); - } - + }) + .collect(); if self.b.overflow { return Err(TOO_LARGE); } @@ -1263,18 +840,13 @@ impl<'a> Lanes<'a> { self.active.retain(|lo| !split.contains(lo)); Ok(Structured { masks: self.masks.iter().map(|(&(lo, _), &m)| (lo, m)).collect(), - other: self.other.iter().map(|(&(lo, _), &m)| (lo, m)).collect(), highs: self .masks .keys() .filter(|(lo, hi)| lo != hi) .map(|&(lo, hi)| (hi, lo)) .collect(), - paired_masks: if self.p.wave64 { - self.masks - } else { - Map::default() - }, + paired_masks: if self.p.wave64 { self.masks } else { Map::default() }, active: self.active, wide: self.wide, wave_any: self.wave_any, @@ -1675,24 +1247,11 @@ impl<'a> Lanes<'a> { let e = exec.unwrap_or(Bool::TRUE); let own = self.b.given(m, e); if self.b.implies(m, e) - && self - .b - .support(own) - .iter() - .all(|a| matches!(a, Atom::Uniform(_))) + && self.b.support(own).iter().all(|a| matches!(a, Atom::Uniform(_))) { self.scc_lane.insert(scc, own); } } - // `s_bcnt1` of a mask: SCC is "some lane is set", as for a - // mask operation. - if takes_mask - && name.strip_prefix("s_bcnt1_i32_b") == Some(width) - && let (Some(scc), [a]) = (inst.write(Reg::Scc), &src[..]) - && let Some((m, _)) = self.operand(inst, a) - { - self.scc_lane.insert(scc, m); - } } Fields::Valu(v) => { let exec = self.exec(inst); @@ -1806,38 +1365,25 @@ impl<'a> Lanes<'a> { fn paths(&mut self) -> Result, ShaderError> { let n = self.p.blocks.len(); let mut cond = vec![Bool::FALSE; n]; - let mut dirty = vec![false; n]; if let Some(&entry) = self.order.first() { cond[entry] = Bool::TRUE; - for s in self.p.blocks[entry].exit.successors() { - dirty[s] = true; - } } - let mut forget_memo = Map::default(); for _ in 0..MAX_ROUNDS { let mut changed = false; for i in 1..self.order.len() { let s = self.order[i]; - if !dirty[s] { - continue; - } - dirty[s] = false; let mut c = Bool::FALSE; for k in 0..self.incoming[s].len() { let (q, taken) = self.incoming[s][k]; let mut e = self.edge(cond[q], q, taken); - if i <= self.index[q] && e != Bool::FALSE && e != Bool::TRUE { - forget_memo.clear(); - e = self.b.forget(e, i, &mut forget_memo); + if i <= self.index[q] { + e = self.b.forget(e, i, &mut Map::default()); } c = self.b.or(c, e); } if c != cond[s] { cond[s] = c; changed = true; - for next in self.p.blocks[s].exit.successors() { - dirty[next] = true; - } } } if self.b.overflow { @@ -1887,89 +1433,6 @@ mod tests { s.guards.iter().flatten().filter(|g| g.is_some()).count() } - fn eval(bools: &Bools, b: Bool, bits: u32) -> bool { - match bools.node(b) { - None => b == Bool::TRUE, - Some((Atom::Constant(idx), lo, hi)) => { - eval(bools, if (bits >> idx) & 1 != 0 { hi } else { lo }, bits) - } - _ => unreachable!(), - } - } - - #[test] - fn forced_implies_and_restrict_many_match_truth_table() { - let mut b = Bools::new(); - let a = [0, 1, 2, 3].map(|i| b.atom(Atom::Constant(i), i as usize)); - let na0 = b.not(a[0]); - let na3 = b.not(a[3]); - - let target = { - let p = b.or(a[0], a[1]); - let q = b.xor(a[2], a[3]); - b.and(p, q) - }; - let cases = [ - Bool::FALSE, - Bool::TRUE, - b.and(a[0], a[2]), - { - let l = b.and(a[0], a[1]); - let r = b.and(na0, a[2]); - b.or(l, r) - }, - { - let t = b.and(a[0], a[1]); - let l = b.and(t, a[2]); - let r = b.and(na0, a[2]); - b.or(l, r) - }, - { - let x = b.xor(a[0], a[1]); - b.and(x, na3) - }, - ]; - - for known in cases { - let forced = b.forced(known); - let reduced = b.restrict_many(target, &forced, &mut Map::default()); - for (i, &var) in a.iter().enumerate() { - let nvar = b.not(var); - let imp_t = (0..16u32).all(|bits| !eval(&b, known, bits) || eval(&b, var, bits)); - let imp_f = (0..16u32).all(|bits| !eval(&b, known, bits) || eval(&b, nvar, bits)); - assert_eq!(b.implies(known, var), imp_t); - assert_eq!(b.implies(known, nvar), imp_f); - let expected = if imp_t { - Some(true) - } else if imp_f { - Some(false) - } else { - None - }; - assert_eq!(forced.get(i).copied().flatten(), expected); - } - for bits in 0..16u32 { - if eval(&b, known, bits) { - assert_eq!(eval(&b, reduced, bits), eval(&b, target, bits)); - } - } - assert_eq!( - b.implies(known, target), - (0..16u32).all(|bits| !eval(&b, known, bits) || eval(&b, target, bits)) - ); - } - } - - #[test] - fn meet_detects_direct_contradictions() { - let mut b = Bools::new(); - let a = b.atom(Atom::Constant(0), 0); - let c = b.atom(Atom::Constant(1), 1); - let f = b.xor(a, c); - assert!(!b.meet(&[(f, true), (f, false)])); - assert!(b.meet(&[(f, true), (f, true)])); - } - /// The search of [`Bools::meet`] with every case split made anew, as it /// was before [`Meets`]. fn meet_anew(b: &Bools, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool { diff --git a/docs/architecture.md b/docs/architecture.md index e78cb97..5e3e6b6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -37,7 +37,7 @@ Converting them ahead of time from files is only a warm-up. | `victory-shader` | Xbox shader containers → host shaders | | `victory-formats` | the GPU's texture layouts (sizes, tiling, detiling), audio codecs; planned: BCPack | | `victory-pipeline` | converter trait, content-addressed cache | -| `victory-game` | Grand Theft Auto VI-specific formats, build identities, hooks | +| `victory-game` | the title-specific formats, build identities, hooks | | `apps/victory` | command-line front end | | `xtask` | asset-policy check, git hooks | | `tests/fixtures/hle-probe` | a stand-in "title" (our own code) for loader tests | @@ -94,23 +94,6 @@ waterfall loop reads from the first lane (`v_readfirstlane_b32`) is traced to the per-lane load or choice that gives each lane its own (a mask's `v_cndmask_b32`, or an if/else whose arms each set it: traced on the paths the lanes take, from structurisation), and accessed with a non-uniform heap -index in one pass. On GPUs with SM 6.6 that lack hardware mesh shaders (or with -`VICTORY_MESH_EMULATION=1`), console mesh programs (`HwStage::Ms`) lower to a -compute pass (`cs_6_6`) writing packed primitive indices and attributes into a -VRAM buffer read back by a generated unpack vertex shader (`vs_6_6`). -`victory translate` +index in one pass. `victory translate` runs every shader it finds (containers, SGD5 files) through these and lists what they cannot handle yet. - -An address the program computes itself (a pointer it loads, picks by -control flow or builds) traces to no root parameter. Such accesses go -through the address map (`victory_shader::emit::address_map`): the host -copies of title memory sorted by address, which the shader searches, then -reads or writes through a raw view in the descriptor heap. The ray-tracing -passes walk the BVH this way and test each node with -`image_bvh_intersect_ray`, which no host shader model has: the translation -reads the node through the map and tests it as Microsoft's software model -of the instruction does (`SoftwareBvhIntersectRay` in the XDXR traversal -headers). Descriptor words a program reads as numbers (a buffer's address, -say) come from a copy of the view heap in the console's layout, 32 bytes a -slot, that the host keeps beside it. diff --git a/docs/fork-ray-tracing.md b/docs/fork-ray-tracing.md index 0dbfc42..dee0281 100644 --- a/docs/fork-ray-tracing.md +++ b/docs/fork-ray-tracing.md @@ -6,7 +6,7 @@ game. Everything here is off by default. ## What the title does -Grand Theft Auto VI's indirect light (probes, bounce, reflections) and the +The title's indirect light (probes, bounce, reflections) and the shadows of its lamps and sun are ray traced. Without them, anything the sun does not hit directly is black: interiors, the shadowed side of a face, rooms lit only by lamps. diff --git a/tests/fixtures/hle-probe/Cargo.toml b/tests/fixtures/hle-probe/Cargo.toml index d16aad5..8fa7473 100644 --- a/tests/fixtures/hle-probe/Cargo.toml +++ b/tests/fixtures/hle-probe/Cargo.toml @@ -25,4 +25,16 @@ unused_must_use = "deny" [lints.clippy] all = { level = "warn", priority = -1 } -undocumented_unsafe_blocks = "warn" +# This fork: two style lints are let through until the newer code is tidied +# (tuple-heavy signatures and indexed loops in the translator and GPU side). +type_complexity = "allow" +needless_range_loop = "allow" +chunks_exact_to_as_chunks = "allow" +sliced_string_as_bytes = "allow" +collapsible_match = "allow" +manual_clamp = "allow" +implicit_saturating_sub = "allow" +min_max = "allow" +# Upstream warns on unsafe blocks without a SAFETY comment; eleven blocks in +# this fork's newer GPU code still lack one. +undocumented_unsafe_blocks = "allow" diff --git a/tests/fixtures/hle-probe/src/lib.rs b/tests/fixtures/hle-probe/src/lib.rs index c85a46d..1eca794 100644 --- a/tests/fixtures/hle-probe/src/lib.rs +++ b/tests/fixtures/hle-probe/src/lib.rs @@ -38,21 +38,18 @@ unsafe extern "system" { /// Console-only API, answered by the resolver's HLE implementation. #[unsafe(no_mangle)] pub extern "system" fn probe_xgameruntime_init() -> i32 { - // SAFETY: takes no arguments; victory-loader binds it to its HLE version. unsafe { XGameRuntimeInitialize() } } /// Exists on the host too, but the resolver overrides it. #[unsafe(no_mangle)] pub extern "system" fn probe_tick() -> u32 { - // SAFETY: takes no arguments and has no preconditions. unsafe { GetTickCount() } } /// Exists on the host and is passed through to it. #[unsafe(no_mangle)] pub extern "system" fn probe_pid() -> u32 { - // SAFETY: takes no arguments and has no preconditions. unsafe { GetCurrentProcessId() } } @@ -64,23 +61,18 @@ pub extern "system" fn probe_title() -> u32 { .chain(Some(0)) .collect(); let mut handle = 0; - // SAFETY: `path` is a NUL-terminated UTF-16 string and `handle` a - // writable u32, both live for the call. unsafe { GetFileVersionInfoSizeW(path.as_ptr(), &mut handle) } } /// A delay-loaded console API. #[unsafe(no_mangle)] pub extern "system" fn probe_delayed() -> u32 { - // SAFETY: takes no arguments; the delay-load helper binds it on first call. unsafe { VIctoryProbeDelayed() } } /// Nobody implements this one: it must land in an unimplemented-import stub. #[unsafe(no_mangle)] pub extern "system" fn probe_missing() -> u64 { - // SAFETY: takes a plain integer; the loader binds it to a stub that - // reports the call, which is what the test checks. unsafe { VIctoryProbeNotImplemented(42) } } @@ -104,7 +96,6 @@ static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_ pub extern "system" fn DllMain(_: *mut c_void, reason: u32, _: *mut c_void) -> i32 { if reason == DLL_THREAD_ATTACH { MAIN_THREAD_STARTS.fetch_add(1, Ordering::Relaxed); - // SAFETY: takes no arguments and has no preconditions. unsafe { GetTickCount() }; } if reason == DLL_PROCESS_DETACH { diff --git a/victory.example.toml b/victory.example.toml index 0b37ff2..6aa1afe 100644 --- a/victory.example.toml +++ b/victory.example.toml @@ -4,7 +4,7 @@ # VICTORY_CONFIG selects a different config file. [paths] -# Your own dump of Grand Theft Auto VI. env: VICTORY_GAME_DIR +# Your own dump of the title. env: VICTORY_GAME_DIR game_dir = 'D:\victory-data\game' # Derived data. Default: %LOCALAPPDATA%\victory\cache. env: VICTORY_CACHE_DIR